Delays between promises in promise chain

Related searches

Let's say I am using the following code to run a couple of promises in series:

let paramerterArr = ['a','b','c','d','e','f']
parameterArr.reduce(function(promise, item) {
  return promise.then(function(result) {
    return mySpecialFunction(item);
  })
}, Promise.resolve())

The code simply calls mySpecialFunction (which returns a promise), waits for the promise to be resolved and then calls mySpecialFunction again etc. So the function is called once for every element in the array, in the correct order.

How could I make sure that there is a delay of at least 50 milliseconds between every call of mySpecialFunction(item)?

It is important that the promises are executed in the right order and the execution time of mySpecialFunction varies every time.

I guess a synchronous sleep would work, but I'm not planning to run this code in a separate thread, so it would cause annoying ui freezes in the browser.

I'm not sure if setTimer could somehow be used for this. I mean I can't delay the returning of a promise.

The answers are good, but they wait too long since all the answers wait regardless of whether or not the actual operation took more than 50ms already.

You can use Promise.all for it.

const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
let paramerterArr = ['a','b','c','d','e','f']
parameterArr.reduce(function(promise, item) {
  return promise.then(function(result) {
    return Promise.all([delay(50), mySpecialFunction(item)]);
  })
}, Promise.resolve())

Delay with a promise, The function delay(ms) should return a promise. That promise should resolve after ms milliseconds, so that we can add .then to it, like this: function delay ( ms ) � So the output is the same as in the previous example: 1 → 2 → 4, but now with 1 second delay between alert calls. Returning promises allows us to build chains of asynchronous actions. Example: loadScript. Let’s use this feature with the promisified loadScript, defined in the previous chapter, to load scripts one by one, in sequence:

A really handy utility function to have around is something I call delay():

function delay(t, val) {
    return new Promise(function(resolve) {
        if (t <= 0) {
            resolve(val);
        } else {
            setTimeout(resolve.bind(null, val), t);
        }
    });
}

Then, you can use it in a promise chain like this:

let paramerterArr = ['a','b','c','d','e','f']
parameterArr.reduce(function(promise, item, index) {
  return promise.then(function(result) {
    // no delay on first iteration
    var delayT = index ? 50 : 0;
    return delay(delayT, item).then(mySpecialFunction);
  })
}, Promise.resolve());

You could also make a little utility function for doing the sequential iteration with optional delay:

// delayT is optional (defaults to 0)
function iterateSerialAsync(array, delayT, fn) {
    if (!fn) {
        fn = delayT;
        delayT = 0;
    }
    array.reduce(function(p, item, index) {
        return p.then(function() {
            // no delay on first iteration
            if (index === 0) delayT = 0;
            return delay(delayT, item).then(fn)
        });
    }, Promise.resolve());
}

And, then you would use it like this:

iterateSerialAsync(paramerterArr, 50, mySpecialFunction).then(function(finalVal) {
    // all done here
});

Promises chaining, The whole thing works, because a call to promise.then returns a in the previous example: 1 → 2 → 4, but now with 1 second delay between� Promises are one of the ways we can deal with asynchronous operations in JavaScript. Many people struggle with understanding how Promises work, so in this post I will try to explain them as simply as I can. Promises are a broad topic so I can't go into every detail in this article. But you'll find an overall introduction to what Promises are, explanations of terms like resolve, reject, and

To get a delay of at least 50ms, use Promise.all:

function delay(t) {
  return new Promise(function(resolve) {
    setTimeout(resolve, t);
  });
}
parameterArr.reduce(function(promise, item) {
  return promise.then(function() {
    return Promise.all([
      mySpecialFunction(item),
      delay(50)
    ]);
  });
}, Promise.resolve());

Delays between promises in promise chain, Delays between promises in promise chain - javascript. You can use Promise. all for it. const delay = ms => new Promise(resolve => setTimeout(resolve, ms));� The next step of the chain will not be performed until the preceding one is resolved. The chains of promises also involve error propagation. The chain of promises may be handled once. As a rule, chaining promises is performed with the following methods of the promise object prototype: .then and .catch.

The following shows an example of how you might achieve a promise that doesn't block but waits for a designated time period:

function timedPromise(ms, payload) {
    return new Promise(function(resolve) {
        setTimeout(function() {
            resolve(payload);
        }, ms);
    })
}


var time = Date.now();

timedPromise(1000)
    .then(function() {
        console.log(time - Date.now());
        return timedPromise(2000);
    }).then(function() {
        console.log(time - Date.now());
        return timedPromise(3000);
    });

So, depending on exactly what you want, you should be able to do something like this:

let paramerterArr = ['a','b','c','d','e','f']
parameterArr.reduce(function(promise, item) {
  return promise.then(function(result) {
    return mySpecialFunction(item);
  }).then(function(specialResult) {
    return timedPromise(50, specialResult);
  });
}, Promise.resolve())

Writing a Promise-Delayer in JavaScript, A simple way of implementing a delay promise that will delay the execution of the next promise in the chain. Since I am working with promises, I wanted a simple way to delay the execution What The DelayPromise practically does is take the result from the last promise, wait N milliseconds and resolve. Promises are an excellent way to reduce the chances of being exiled to callback hell. In node.js I've been using the promising module Q to handle the flow of asynchronous code. If you have a number of things you'd like to do in a specific order, you can set up a promise chain by using something like:

Here you go: https://jsbin.com/suvasox/edit?html,js,console

let paramerterArr = ['a','b','c','d','e','f']
paramerterArr.reduce((p, val) => {
  return p.then(() => {
    return new Promise((res) => {
      setTimeout(() => { res(mySpecialFunction(val)); }, 1000); 
    });
  });
}, Promise.resolve());

p has to be the result of the p.then(). Only that way you chain the promises.

Notice, I changed it to 1000ms delay just for emphasis.

Promise.delay, Bluebird is a fully featured JavaScript promises library with unmatched Promise .delay(500).then(function() { console.log("500 ms passed"); return "Hello world"� That’s very convenient, because finally is not meant to process a promise result. So it passes it through. We’ll talk more about promise chaining and result-passing between handlers in the next chapter. Last, but not least, .finally(f) is a more convenient syntax than .then(f, f): no need to duplicate the function f.

If a promise is rejected, then every subsequent promise in the chain will be rejected, until one is reached with an error callback.

We should observe, then, that promises can be chained “arbitrarily”, that is to say: as we just saw, you can save a reference to any point in the promise chain and then tack more promises on top of it. This is one of the fundamental points to understanding promises. You can save a reference to any point in the promise chain.

Cancelling a Promise only prevents its resolve and reject callbacks from running. Adding additional abort semantics where possible is great for operations that you can do so for. One prime benefit of cancellation via Promises is that if you cancel a Promise that’s part of a chain, it will also cancel all of the other pending Promises in that

Comments