为有延迟的请求处理创建承诺链

Create a Promise Chain for Request Handling with Delays

我想创建一个从服务器获取数据的请求链,但在每个请求之间应该有 X 秒的延迟。

应该是这样的:

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

但是,我没有按照我的意愿进行操作。它立即触发所有请求,然后进入响应处理程序。最后部分在数据填充之前被调用。

因为你使用的是bluebird,使用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
});

或者 - 使用您的 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
});