前言
使用promise进行异步操作的同步表达,可以解决过往使用回调函数导致的回调地狱。
但是在实际场景下,有时候由于开发人员理解不深入,会错误地把promise写成回调的模样。
本文以setTimeout代表异步操作,本质模拟的是多步连续调用HTTP服务的实际场景。
let counter = 1;
function asyncAction() {
let p = new Promise(function(resolve, reject) {
// 异步
setTimeout(function() {
resolve(counter++);
}, 0);
});
return p;
}
错误的回调写法
promise 错用回调的情况,在执行then中直接调用下一个promise异步方法。
asyncAction().then(res => {
console.log(res);
asyncAction().then(res=>{
console.log(res);
asyncAction().then(res=>{
console.log(res);
})
})
});
链式写法
promise 实现真正的链式异步操作时,每一步then以后应该return新的promise。
asyncAction()
.then(res => {
console.log(res);
return asyncAction();
})
.then(res => {
console.log(res);
return asyncAction();
})
.then(res => {
console.log(res);
});