[英]How to wait for a function to be executed using promise to wait on its callback in Javascript/Node JS
I have two functions say async foo()
and bar()
我有两个函数说async foo()
和bar()
Lets say exe time of foo()
=> 5 seconds让我们说foo()
exe 时间 => 5 秒
exe time of bar()
=> 10 seconds bar()
时间 => 10 秒
Code looks something like代码看起来像
await foo();
async foo(){
//body
bar()
}
PROBLEM:问题:
Here foo()
takes 5 seconds to execute (the body part) so it returns a successful promise without waiting for the execution of bar()
to complete这里foo()
执行(主体部分foo()
需要 5 秒,因此它返回一个成功的承诺,而无需等待bar()
的执行完成
QUESTION:题:
How do i make sure that foo()
only returns a promise when bar()
completes its execution maybe using promise to wait on the callback of bar()
but i'm not sure how to exactly go about it我如何确保foo()
仅在bar()
完成其执行时才返回承诺,也许使用承诺等待bar()
的回调,但我不确定如何确切地去做
Note: Can't declare bar as async since it is imported from some other module注意:不能将 bar 声明为异步,因为它是从其他模块导入的
You can promisify methods of aws-sdk
's services just by appending the method with .promise
;您可以promisify的方法aws-sdk
只是通过附加与方法的服务.promise
;
await foo();
foo(){
return ses.sendTemplatedEmail(params).promise();
}
OR或者
await foo();
async foo(){
try {
let res = await ses.sendTemplatedEmail(params).promise();
console.log(res)
}catch(err) {
console.log(err)
}
}
You can try below code你可以试试下面的代码
await foo();
foo() {
return new Promise(async resolve => {
const result =await bar()
if (result) {
resolve(true)
}
})
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.