Promise的基本用法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| let promise = new Promise((resolve, reject) => { console.log(1) console.log(2) resolve('success') })
promise.then(res => { console.log(3) })
promise.catch(err => { console.log(err) console.log(4) })
|
在Promise
的内部,执行顺序是同步的。其次等内部执行完成后,调用再选择调用then
orcatch
方法。
所以这次输出的结果:
1
2
3
then的执行顺序
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| let promise = new Promise((resolve, reject) => { console.log(1) console.log(2) resolve('success') })
promise.then(res => { console.log(res) console.log(3) })
console.log(5)
|
then
方法执行是异步的,不用等到then
的方法结果,会直接执行console.log(5)
1
2
5
3
我们可以根据上面的代码,丰富业务实际情况
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| let promise = new Promise((resolve, reject) => { console.log(`开始执行`) resolve('success') console.log(`执行中ing`) }).then(res => { console.log(res) console.log('执行成功,继续执行下一步') return '第二then方法,开始' })
promise.then(res => { console.log(res) })
console.log(`我会在then方法前,先执行`)
setTimeout(()=>console.log(`then方法执行完成后,开始执行`))
|
执行结果:
1.开始执行
2.执行中ing
3.我会在then方法前,先执行
4.执行成功,继续执行下一步
5.第二then方法,开始
6.then方法执行完成后,开始执行
总结
其实比较好理解的方式是:每次当promise
执行完成后,then
是异步的,所以当执行then
后,不会等它的结果,会直接执行下面的代码,但是setTimeout
定时器本身会将执行内容调到任务队列
尾部,所以会等then
方法执行完成后才会调用定时器。