-
Notifications
You must be signed in to change notification settings - Fork 6
Open
Description
对于异步编程,使用 Promise 是一种非常棒的实践,利用 then 方法的链式调用,可以让我们的代码清晰明了,但链式调用是串行的,如果编程中需要并行处理怎么办?例如我们有多个异步事件,它们之间并无联系而且没有先后顺序,但需要全部完成才可以进行下一步工作。你可能会说可以用 Promise.all,这的确是一种解决方式,这里推荐更棒的一种方式是 async/await 方法。
async/await 是基于 Promise 的语法糖,可以让我们以同步代码的组织形式来完成异步编程。
注意:当一个函数声明为
async时,内部可以没有await,但一个内部包含await方法的函数,一定得是async函数。
async function timeout(seconds) {
if (seconds > 0) {
let result = await new Promise(resolve => {
setTimeout(() => {
console.log(`await 代码执行完毕`);
resolve(`hello world`);
}, seconds * 1e3);
});
console.log(`我是 await 后面的代码`);
return result;
} else {
throw `TypeError: \`seconds\` should be a number, and more than zero`;
}
}
timeout(1).then(res => console.log(`输出结果:`, res));
console.log(`虽然在后面,但我先执行`);Metadata
Metadata
Assignees
Labels
No labels