简体   繁体   中英

Create a Promise Chain for Request Handling with Delays

I want to create a chain of requests that get data from a server, but between each request a delay of X seconds should happen.

Should go like this:

const data = {};
const promises = Promise.resolve();
for (let elem of longArray) {
    promises.then(() => {
        return sendRequest(); // returns promise
    })
    .then((response) => {
        // Store response stuff in data
    })
    .then(() => {
        // Wait here for X seconds before continuing
    })
}

promises.finally(() => {
    // Log stuff from data
});

However, I don't get it doing what I want. It immediately fires all requests and then goes in the response handler. And the finally part is called before the data was filled.

As you are using bluebird, it's very simple using array.reduce

const data = {};
longArray.reduce((promise, item) => 
    promise
        .then(() => sendRequest())
        .then(response => {
            // Store response stuff in data
        }).delay(X), Promise.resolve())
.finally(() => {
    // Log stuff from data
});

or - using your for...of loop

const data = {};
const promises = Promise.resolve();
for (let elem of longArray) {
    promises = promises
    .then(() => sendRequest())
    .then(response => {
        // Store response stuff in data
    })
    .delay(X);
}

promises.finally(() => {
    // Log stuff from data
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM