Async / Await 问题
首先简单总结, Async和Await 可以将异步操作像写同步操作那样简单
注意: await 所等待的函数必须返回对象为Promise,如果不是 需要 return new promise 才可以
let promise = new Promise((resolve, reject) => {
// 异步函数执行成功时执行回调,若resolve函数有带参数,则该参数会传递给回调函数
resolve()
// 异步函数执行失败时执行回调,若reject函数有带参数,则该参数会传递给回调函数
reject()
})
function setTime(time) {
return new Promise((reslove)=>{
setTimeout(() => {
console.log(time)
reslove() // 自执行成功函数
}, time);
})
}
function setTime(time) {
return new Promise((res)=>{
setTimeout(() => {
console.log(time)
res()
}, time);
})
}
let main = async function() {
await setTime(100)
console.log('执行到1')
await setTime(1000)
console.log('执行到2')
}
main()
这样整个程序就可以将异步按照同步的方法去运行了
注意,一定要把需要回传的参数放在reslove中,如果没有 也要把reslove 执行一下,不然Promise会被中断,如下