昨天有个小猪问我 async/await 的问题, 说是怎么调也调不出想要的结果, 调着调着头都懵了
扭头过去看了一下, 果不其然, 一层套一层简直比俄罗斯还套娃
不过只要静下心来, 对照着下面的几点特性慢慢看, async/await 还是很好理解的
- Promise 对象不需要用 () 调用
- 实例化 Promise 时, 第一个传入的 function 会马上执行了
var _promise = new Promise(function() { /* 这里直接就执行了 */ })
- async 函数还是函数, 用 () 执行后才是 Promise 对象
- (await _promise) 是 _promise 报 resolve 时传回来的内容
- await 只能在 async 函数中使用
- await 后跟一个 promise 对象会阻塞代码, 直到 promise 报 resolve; 不是 promise 对象则不作处理
- await 后跟的代码无论是什么都会马上执行, 是 promise 对象时, 阻塞的是后面的代码
- await 后跟的 promise 报 reject 时, 代码报错
- _promise 报 resolve 时 await _promise 和 _promise.then() 差不多
console.log(await _promise)
_promise.then(function(params) {
console.log(params)
})
- _promise 报 reject 时 await _promise 报错, 结合 try…catch 和 _promise.catch() 差不多
try {
await _promise
} catch(error) {
console.log(error)
}
_promise.catch(function(params) {
console.log(params)
})
end