[英]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
});
但是,我沒有做我想要的事情。 它立即觸發所有請求,然后進入響應處理程序。 最后一部分在填充數據之前被調用。
當您使用藍鳥時,使用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
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.