简体   繁体   English

创建承诺链以处理延迟请求

[英]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. 我想创建一个从服务器获取数据的请求链,但是在每个请求之间应该发生X秒的延迟。

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 当您使用蓝鸟时,使用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 或-使用for ... of循环

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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