[英]Call a function only after other async/await functions are resolved
I am calling 2 functions after a click event.我在单击事件后调用 2 个函数。
These function calls are present in a singInHandler()
这些 function 调用存在于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.要求:我想调用第 3 个 function window.customAuth.getId()
但只有在执行上述 2 个函数和相应的响应后才能调用它。
window.customAuth.init(configFile)
@returns {Promise} A promise with the user data. window.customAuth.init(configFile)
@returns {Promise} 带有用户数据的 promise。
window.customAuth.login()
@returns {Promise} 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.将您的承诺放入数组中,然后调用Promise.race
,它将在 1 promise 得到解决后立即得到解决。
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.如果你想检查前 2 个函数的返回值,那么……就去做吧。
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();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.