实现方法调用后如下:
let count = 1;
let promiseFunction = () =>
new Promise(rs =>
setTimeout(() => {
rs(count++);
})
);
lastFn().then(console.log); // 无输出
lastFn().then(console.log); // 无输出
lastFn().then(console.log); // 3
实现方案:
function test (myPromise) {
let arr = []
let target = ''
function fn () {
arr.push(myPromise)
return {
then
}
}
function then (fn) {
clearTimeout(target)
target = setTimeout(() => {
arr.forEach((item, index) => {
item().then(res => {
if (arr.length - 1 === index) {
fn(res)
}
})
})
})
}
return fn
}
let lastFn = test(promiseFunction)
lastFn().then(res => {
console.log(res)
}); // 无输出
lastFn().then(res => {
console.log(res)
}); // 无输出
lastFn().then(res => {
console.log(res)
}); // 3