为延迟请求处理创建承诺链
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 ...循环数
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
});
相关文章:
- 创建具有蓝鸟承诺的节流功能
- 如何创建角度承诺中捕获的错误
- 我可以在不创建延期的情况下报告Q承诺进度吗
- 同步异步创建的承诺
- 创建承诺回调
- 在猫鼬中创建承诺时,不会调用执行器
- 并行创建承诺
- 如何在 mpromise 中创建已兑现的承诺
- 在Selenium webdriver javascript绑定中创建“自定义”承诺
- 创建一个成功/错误的承诺,例如像ajax
- 我可以创建一个承诺来检查变量是否设置为角度吗?
- 如何在返回承诺的服务中创建 reset() 方法
- 为延迟请求处理创建承诺链
- 在承诺链中创建错误
- 基于当前平台创建承诺对象
- 角度 |创建链式承诺
- 在这种情况下,我将如何使用 javascript 创建一个承诺函数
- 使用BB承诺创建具有空闲端口的服务器
- 动态添加内容到Angular承诺创建的元素中
- 使用承诺创建用户和登录流