例如有下面3个函数
function a() {
b();
c();
}
function b() {
setTimeout(() => {
console.log('b')
}, 2*1000);
}
function c() {
setTimeout(() => {
console.log('c')
}, 1*1000);
}
a() //输出结果分布是:c,b
如果我们相要让他们按顺序输出b,c就不是很容易的了,因为settimeout函数是一个异步执行的事件,所以es6提供了一个async await配合promise方法来解决这个问题,
改写成下面代码
async function a() {
await b()
await c()
}
function b() {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log('b')
resolve(1)
}, 2 * 1000);
})
}
function c() {
return new Promise((resolve, reject) => {
console.log('c')
resolve(2)
})
}
a()//输出:b,c
es6提供的async await 方法十分强大,但要配合promise来使用才能展现他的真正功能,具体的async await和promise用法可以百度了解一下
参考链接:https://www.jianshu.com/p/73b070eebf50
