编辑代码

/**
 * 只有最后一次promise会then与reject
 * @param {function} promiseFunction
 * promiseFunction 示例: () => fetch('data')
 */
function lastPromise(promiseFunction) {
    let count = 0;
    return function () {
        count++;
        let id = count;
        return new Promise((resolve, reject) => {
            // 这里的内容丢入微队列里,所以最后只有count = 3 和id为3的那个会执行
            promiseFunction().then((resp) => {
                if (id === count) {
                    resolve(resp);
                }
            });
        });
    };
}
// 示例
let count = 1;

// 生成一个个的 promise
let promiseFunction = () =>
    new Promise(rs =>
        setTimeout(() => {
            rs(count++);
        })
    );


let lastFn = lastPromise(promiseFunction);
lastFn().then(console.log); // 无输出
lastFn().then(console.log); // 无输出
lastFn().then(console.log); // 3