简体   繁体   中英

Call a function only after other async/await functions are resolved

I am calling 2 functions after a click event.

These function calls are present in a singInHandler()

  signInHandler = async () => {
      await window.customAuth.init(configFile);    
      await window.customAuth.login();
  }

Requirement : I want to call a 3rd function window.customAuth.getId() but it should be called only after the above 2 functions are executed with respective responses.

window.customAuth.init(configFile) @returns {Promise} A promise with the user data.

window.customAuth.login() @returns {Promise}

How can I do this?

Put your promises into the array and then call Promise.race , it will get resolved as soon as 1 promise gets resolved.

or shorter:

Promise.race([window.customAuth.init(configFile), window.customAuth.login()]).then(() => {
    // logic here
})

You can just repeat what you already did.

signInHandler = async () => {
      await window.customAuth.init(configFile);    
      await window.customAuth.login();
      await window.customAuth.getId();
  }

If you want to check return-values of the previous 2 functions, then... just do it.

signInHandler = async () => {
      const result1 = await window.customAuth.init(configFile);    
      const result2 = await window.customAuth.login();
      if (result1 === true || check whatever you want) {
            await window.customAuth.getId();
      }
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM