我有这个。
const getPrice = function(database){
return new Promise(function (resolve, reject){
var promises =[];
for(var i in database){
promises.push(Update.requestClassifieds(database[i]))
}
Promise.all(promises)
.then(function(todos){
return resolve(todos);
})
})}
Update.prototype.requestClassifieds = function(item){
var ithis = this;
return new Promise((resolve, reject) => {
var input = {};
request({
url: '',
method: "GET",
json: true,
body: input
}, function (error, response, body){
if (error){
return resolve(item);
}
else if(body){
return resolve(item);
}
}
});
});
}
我需要为数据库中的每个项目请求数据。所以,我为此创造了一个承诺链。
我正在请求具有 5 秒冷却时间的 api 的数据。因此,我需要等待 5 秒,直到解决 Promise.all(promises) 中的下一个承诺。
如何在 Promise.all 中的每个承诺之间设置超时?
你需要
在你的循环中创建Promise
链
const getPrice = function (database) {
var promisesChain = Promise.resolve(); // Promise chain
var todos = []; // results to be stored
for (var i in database) {
promisesChain = promisesChain.then(((i) => () => { // create closure to grab database[i]
return Update.requestClassifieds(database[i])
})(i)).then((res) => {
return new Promise((resolve, reject) => {
setTimeout(() => { // store result of requestClassifieds and resolve after 5sec
todos.push(res);
resolve();
}, 500);
});
})
}
return promisesChain.then(() => {return todos});
};
运行示例
const getPrice = function (database) {
var promisesChain = Promise.resolve();
var todos = [];
for (var i in database) {
promisesChain = promisesChain.then(((i) => () => {
return Update.requestClassifieds(database[i])
})(i)).then((res) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
todos.push(res);
resolve();
console.log('resolve', res);
}, 1000);
});
})
}
return promisesChain.then(() => {return todos});
};
const Update = {};
Update.requestClassifieds = function (i) {
console.log('got', i);
return new Promise((resolve, reject) => {
resolve(i)
});
}
getPrice({
a: 'A',
b : 'B',
c : 'C'
}).then(console.log);