【发布时间】:2020-03-17 10:39:19
【问题描述】:
我想为一个承诺设置一个超时时间。
错误信息:
Status is OVER_QUERY_LIMIT. You have exceeded your rate-limit for this API.
所以,要每秒钟执行一次 API,我需要在 Promise 中设置一个超时时间。但是下面我的代码不起作用...
我的代码:
CoordinateModel.findAll().then(function(findedCoordinates) {
var promises = [];
promises = findedCoordinates.map(function(coordinate) {
return new Promise(function() {
setTimeout(function() {
return geocoder.geocode(coordinate.address + ' ' + coordinate.postcode + ' ' + coordinate.city + ' ' + coordinate.complementaryAddress).then(function(res) {
return coordinate.update({
lng: res[0].longitude,
lat: res[0].latitude
}).then(function() {
console.log(coordinate.name + ' : ' + res[0].longitude + ',' + res[0].latitude);
return Promise.resolve();
});
}).catch(function(err) {
console.log(err);
return Promise.reject();
});
}, 1000);
});
});
Promise.all(promises).then(function() {
console.log('------ END ------');
});
});
【问题讨论】:
-
你需要解析你在
.map函数中返回的new Promise,否则你的proimses将永远不会返回。 -
好的,但它不适用于我的代码,
geocode()函数不是每秒钟执行一次... -
关于每秒只处理一个请求,有几个选项,但最基本的一个是你给
setTimeout函数的数字应该每次迭代增加1000。跨度> -
按照你现在的方式,所有的 Promise 都会在一秒钟内处理完毕。
-
让它每次迭代增加 1000 的简单方法是知道
.map函数将索引作为第二个参数.map(function(element, index)) ... setTimeout(f(), 1000*index)。如果你跟随。
标签: javascript promise timeout