Muhammad Umer
Muhammad Umer

Reputation: 18127

Create a function that no matter how many times invoked run only when first async call finishes?

suppose I've a function fetch(id).

I would be calling it arbitrarily at random times.

But I want every successive call to run only after previous call has finished.

say the async task takes 4 seconds, and i call fetch 3 times. then total time should be 12 seconds.

I could make a array and at every call set promise to go through next in line.

but what are some ways to accomplish this.

Upvotes: 0

Views: 45

Answers (3)

Konstantin Lekh
Konstantin Lekh

Reputation: 71

You can chain Promises without an array, just store a pointer to the last 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);
}

Upvotes: 1

Muhammad Umer
Muhammad Umer

Reputation: 18127

I think I got it

//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);

Upvotes: 1

Rictus
Rictus

Reputation: 112

I guess you can use async.io library. Or, each time you want to call your function, push the function itself in an array. When the previous function has finished, check if there is still some functions to call in the array.

Upvotes: 0

Related Questions