Promise构造函数和then方法的执行顺序
Promise的基本用法
let promise = new Promise((resolve, reject) => {
console.log(1)
// 如果执行失败,则调用reject()
// reject('fail')
console.log(2)
// 如果执行成功,则调用resolve()
resolve('success')
})
// 如果执行成功,则继续调用then方法
promise.then(res => {
// console.log(res)
console.log(3)
})
// 如果执行失败,则用catach捕获失败
promise.catch(err => {
console.log(err)
console.log(4)
})在Promise的内部,执行顺序是同步的。其次等内部执行完成后,调用再选择调用thenorcatch方法。
所以这次输出的结果:
1
2
3
then的执行顺序
let promise = new Promise((resolve, reject) => {
console.log(1)
// 如果执行失败,则调用reject()
// reject('fail')
console.log(2)
// 如果执行成功,则调用resolve()
resolve('success')
})
// 如果执行成功,则继续调用then方法
promise.then(res => {
console.log(res)
console.log(3)
})
// promise内部是同步的,但是then方法是异步的
console.log(5)then方法执行是异步的,不用等到then的方法结果,会直接执行console.log(5)
1
2
5
3
我们可以根据上面的代码,丰富业务实际情况
let promise = new Promise((resolve, reject) => {
console.log(`开始执行`)
// 如果执行成功,则调用resolve()
resolve('success')
console.log(`执行中ing`)
}).then(res => {
console.log(res)
console.log('执行成功,继续执行下一步')
return '第二then方法,开始'
})
// 如果执行成功,则继续调用then方法
promise.then(res => {
console.log(res)
})
// promise内部是同步的,但是then方法是异步的
console.log(`我会在then方法前,先执行`)
// 我们可以利用timeout方法在then方法执行完成后,进行执行
setTimeout(()=>console.log(`then方法执行完成后,开始执行`))执行结果:
1.开始执行
2.执行中ing
3.我会在then方法前,先执行
4.执行成功,继续执行下一步
5.第二then方法,开始
6.then方法执行完成后,开始执行
总结
其实比较好理解的方式是:每次当Promise执行完成后,then是异步的,所以当执行then后,不会等它的结果,会直接执行下面的代码,但是setTimeout定时器本身会将执行内容调到任务队列尾部,所以会等then方法执行完成后才会调用定时器。
相关推荐
88520191 2020-06-13
Magicsoftware 2020-05-26
88254251 2020-11-01
MarukoMa 2020-09-02
88234852 2020-09-15
陈旭阳 2020-08-31
whynotgonow 2020-08-19
前端开发Kingcean 2020-07-30
whynotgonow 2020-07-29
bowean 2020-07-08
前端开发Kingcean 2020-07-08
88520191 2020-07-05
前端开发Kingcean 2020-06-27
88481456 2020-06-18
whynotgonow 2020-06-16
88520191 2020-06-13