在settimeout内承诺

我试图在彼此延迟1秒的时间内执行承诺,因为我正在使用的API服务器每秒有一个请求限制。

这是我的代码目前

var delay = 0; return categories.reduce(function(promise, category) { var id = setTimeout(function() { promise.then(function() { return client.itemSearch({ searchIndex: configuration.SearchIndex, CategoryID: category.id, Keywords: currentKeyword }).then(function(results) { var title = results[0].Title; var cat = category.name; var price = results[0].Price; return db.insertProduct(title, cat, price); }); }).catch(function(err) { console.log("error", err); }); }, delay * 1000); delay += 1; }, Promise.resolve()); 

每次循环时,都会延迟1秒,以使下一个项目以1秒的延迟开始。

所以如果它的第一项,它的0 * 1 = 0,那么1 * 1 = 1,那么2 * 1 = 2 …等等

由于某种原因,它不起作用,没有settimeout它完美的作品。

据我所知,迟迟不会出现承诺的问题,除非在延迟结束之后可能与variables没有正确的值有关。 如果是这样的话,我该如何解决这个问题,也许是传递variables?

我感谢我能得到的每一个帮助。

使用async.eachSeries ,您可以在每个请求完成后1秒钟内对每个进行处理,并执行asynchronouscallback:

 async.eachSeries(categories, function(category, callback) { client.itemSearch({ searchIndex: configuration.SearchIndex, CategoryID: category.id, Keywords: currentKeyword }).then(function(results) { // we don't need to wait after the database here, just after the request setTimeout(callback, 1000); var title = results[0].Title; var cat = category.name; var price = results[0].Price; db.insertProduct(title, cat, price); }).catch(callback); }, function(err) { if (err) { console.log('error', err); } });