实现一个类似防抖的函数,只执行最后一个promise

60 阅读1分钟

实现一个函数,接受一个promise,每次调用这个函数,都会执行这个promise,如果连续调用,则只输出最后一个promsie的结果。

let count = 1;

const executeFunction = () => {
  return new Promise((res) => {
    setTimeout(() => {
      res(count++);
    });
  });
};

function promise (promise) {}

const lastFun = promise(promiseFunction);

// lastFun().then(()=>console.log)
// lastFun().then(()=>console.log)
// lastFun().then(()=>console.log)

// 要求以上代码之后后输出
// undefined
// undefined
// 3
// 请实现promise


function myDebouncePromise (promiseFunction) {
  let count=0;
  return async function(...args){
    count++;
    const current = count;
    const re = await promiseFunction(args);
    if(current === count){
      return re;
    }
    return null
  }
}

const lastFun2 = myDebouncePromise(executeFunction);
lastFun2().then((r) => console.log(r));
lastFun2().then((r) => console.log(r));
lastFun2().then((r) => console.log(r));