【问题标题】:Create a function that no matter how many times invoked run only when first async call finishes?创建一个无论调用多少次都只在第一次异步调用完成时运行的函数?
【发布时间】:2017-09-25 20:55:14
【问题描述】:

假设我有一个函数fetch(id)

我会在随机时间任意调用它。

但我希望每个后续调用仅在上一个调用完成后运行。

说异步任务需要 4 秒,我调用 fetch 3 次。那么总时间应该是12秒。

我可以创建一个数组,并在每个调用集承诺通过下一个。

但是有什么方法可以做到这一点。

【问题讨论】:

  • 是的,promise queue 是个不错的方法。

标签: javascript asynchronous


【解决方案1】:

我想我明白了

//First my example function which could be anything but should return promise which would be queued

function example(n) {
    return new Promise((res, rej) => {
        setTimeout(()=> {
            console.log(n);
            res();
        }, 1000);
    });
}


//now solution

function debounce(func) {

    let p = Promise.resolve();

    return function(x){
        p = p.then(() => func(x));
    }
}


//usage

d = debounce(example);
d(1);d(2);d(3);d(4);d(5);d(6);d(1);

【讨论】:

    【解决方案2】:

    你可以在没有数组的情况下链接 Promise,只需存储一个指向最后一个 Promise 的指针

    // async payload function
    // returns a promise
    function f(x) {
      console.log(`call f(${x})`);
      return new Promise((resolve) => {
        setTimeout(() => {
          console.log(`resolve f(${x})`);
          resolve();
        }, 2000);
      });
    }
    
    // wrapper to call function `f` sequentially
    // stores pointer to the last Promise in closure
    const g = (function(){
      let lastPromise = Promise.resolve();
      return function(arg){
        lastPromise = lastPromise.then(() => f(arg));
      }
    })();
    
    // generate random calls of function function `g`
    for (let i = 0; i < 5; i++) {
      setTimeout(() => g(i), Math.random() * 100);
    }
    

    【讨论】:

    • 哇,我得到了相同的解决方案,您可以使用 Promise.resolve() 它将立即运行,因此不需要条件
    【解决方案3】:

    我猜你可以使用async.io 库。 或者,每次你想调用你的函数时,把函数本身压入一个数组。上一个函数执行完毕后,检查数组中是否还有函数需要调用。

    【讨论】:

    • 如何使用 async.js?里面有很多功能在这里绝对没用。
    猜你喜欢
    • 2021-01-04
    • 1970-01-01
    • 1970-01-01
    • 2021-12-03
    • 1970-01-01
    • 1970-01-01
    • 2015-01-01
    • 1970-01-01
    • 2022-11-12
    相关资源
    最近更新 更多