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(`虽然在后面,但我先执行`);
对于异步编程,使用 Promise 是一种非常棒的实践,利用
then
方法的链式调用,可以让我们的代码清晰明了,但链式调用是串行的,如果编程中需要并行处理怎么办?例如我们有多个异步事件,它们之间并无联系而且没有先后顺序,但需要全部完成才可以进行下一步工作。你可能会说可以用Promise.all
,这的确是一种解决方式,这里推荐更棒的一种方式是async/await
方法。async/await
是基于 Promise 的语法糖,可以让我们以同步代码的组织形式来完成异步编程。