通过超时解决一系列承诺。 Promise.all

时间:2017-10-06 16:07:16

标签: javascript node.js request timeout

我有这个。

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(承诺)中的下一个承诺。

如何在Promise.all中的每个promise之间设置setTime?

1 个答案:

答案 0 :(得分:0)

您需要在循环中创建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);