promise是一个很好的解决异步调用的方法,其链式调用也是一个很好的方式,这里探究一下其调用过程
主要问题
Promise.resolve()
.then(res => {
return new Promise()
})
Promise.resolve()
.then(res => {
new Promise()
})
// 上下两种Promise的方式中, 是否会进行下去,以及新产生的promise是否会被传递下去,或者说有什么区别
测试代码
每一句打印后面都输出了时间戳,是为了更好描述运行顺序
测试代码直接贴在下方,可以拿到浏览器中进行测试查看
;(function () {
// fn1()
// fn1_1()
// fn2()
// fn3()
// fn4()
// fn5()
// fn6()
// fn7()
// fn8()
// fn9()
})()
function fn1 () {
console.log('start', new Date().getTime())
new Promise(resolve => {
console.log('11111', new Date().getTime())
}).then(res => {
console.log('22222', new Date().getTime())
}).then(res => {
console.log('33333', new Date().getTime())
})
console.log('end', new Date().getTime())
/*
start 1560165694777
11111 1560165694787
end 1560165694790
*/
}
function fn1_1 () {
console.log('start', new Date().getTime())
new Promise(resolve => {
console.log('11111', new Date().getTime())
resolve()
console.log('11111-1111', new Date().getTime())
}).then(res => {
console.log('22222', new Date().getTime())
}).then(res => {
console.log('33333', new Date().getTime())
})
console.log('end', new Date().getTime())
/*
start 1560166834093
11111 1560166834106
11111-1111 1560166834108
end 1560166834110
22222 1560166834115
33333 1560166834119
*/
}
/*
通过前 fn1, fn1_1 两个小例子可知,最开始的new Promise可能对我们进行干扰,
出现这种状况的原因是,申明 new Promise的时候此时异步还未开始,所以我们
直接按照接下来的方式进行测试
*/
function fn2 () {
console.log('start', new Date().getTime(