我想创建一系列从服务器获取数据的请求,但在每个请求之间应该发生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
});
但是,我没有按照自己的意愿行事。它会立即触发所有请求,然后进入响应处理程序。在数据填满之前调用finally部分。
答案 0 :(得分:2)
当你使用蓝鸟时,使用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
});
或 - 使用你的...循环
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
});