我想创建一个从服务器获取数据的请求链,但是在每个请求之间应该发生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 ...循环数
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
});