Men*_*des 2 javascript async-await
我想连接mongoDb并异步执行代码.
async function test() {
let task = asyncTask() //return a promise
//function still running
await task
//code executed only if task is resolved
}
Run Code Online (Sandbox Code Playgroud)
使用等待是正确的吗?
是的,如果您使用等待异步函数,则代码将阻塞,直到promise已解决或失败.您应该在try catch中包装await块以处理任何错误.
async function test() {
let task = asyncTask()
//function still running
try {
await task
//code executed only if task is resolved
} catch (err){
//Something went wrong
throw new Error(err);
}
}
Run Code Online (Sandbox Code Playgroud)
使用async/await具有与promise相同的功能,但只是提供了一种更加同步的代码编写方式.
如果您想将代码重写为承诺,那么它看起来像:
function test() {
myPromise('some arguments')
.then(result => console.log(`Task completed: ${result}`);)
.catch(err => console.error(err));
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
67 次 |
最近记录: |