说说 Promise 的 then 函数
一个 Promise 在状态为改变之前,绝不会执行它的 then 函数。在状态改变之后才会执行。
给一个 Promise 添加 then 方法的形式有几种。不仅可以链式调用,还可以分开调用。
可以这样理解:then 函数的作用就是将传入 then 方法的函数类型参数推入到对应的 promise 里,当 promise 的状态改变时, 它会依次执行这些函数类型参数。
js
let cachePromise = null;
function getPromise() {
if (cachePromise) return cachePromise;
cachePromise = new Promise(resolve => {
setTimeout(() => {
resolve('hello')
}, 2000)
})
return cachePromise;
}
getPromise().then(() => {
console.log('我也执行了')
})
getPromise().then(res => {
console.log(res)
}).then(() => {
console.log('我又执行到这里了')
})