一般遇到的promise使用方式很少接触到链式调用,今天看了些文章,故写了个例子来理解
链式操作一般的应用场景是后面的then需要前面的then(前面的then应该也是个异步操作,因为若不是异步操作,就可以将代码直接写在前一then里,不需要第二个then)的返回值,故前面的then也需要返回的是promise对象。
const p = new Promise((resolve, reject) => {
setTimeout(() => {
resolve(333);
}, 1000)
});
p.then(res => {
console.log(res);
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('444=====');
}, 5000);
})
}).then(res => {
console.log(res)
})
结果是 等1s 打印333 间隔5s 444====
尝试第一个then里返回的若不是promise对象
const p = new Promise((resolve, reject) => {
setTimeout(() => {
resolve(333);
}, 1000)
});
p.then(res => {
console.log(res);
return "ahhaha";
}).then(res => {
console.log(res)
})
结果是 1s后同时打印333 ahhaha 故只要前一个then return了值,在后一个then里都会拿到这个return的值,但是这样写在真实的场景里没有意义,因为完全不需要第二个then,把代码写在第一个then里就可以了。
尝试在第一个then里隔一段时间间隔再返回一个值,但第一个then返回的不是promise对象
const p = new Promise((resolve, reject) => {
setTimeout(() => {
resolve(333);
}, 1000)
});
p.then(res => {
console.log(res);
setTimeout(() => {
console.log('----睡觉睡觉睡觉');
return '----睡觉睡觉睡觉'
}, 4000);
console.log('----hhh');
}).then(res => {
console.log(res);
})
结果是 1s后同时打印333 ----hhh undefined 间隔4s后打印---睡觉睡觉睡觉
故:若第一个then里通过异步操作返回一个值,但是返回值不是promise对象,第二个then不会等第一个then的异步操作执行完毕,所以打印出undefined,所以若想在第二个then中拿到第一个then的异步操作结果,就必须在第一个then里返回的是一个promise对象。