【问题标题】:Promise inside a settimeout在 settimeout 内承诺
【发布时间】:2016-04-21 12:47:08
【问题描述】:

我正在尝试以 1 秒的延迟运行 Promise,因为我正在使用的 API 服务器每秒有 1 个请求的限制。

这是我目前的代码

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 秒的延迟开始。

所以如果它是第一项,它的 0*1 = 0,然后 1*1 = 1,然后 2*1 = 2... 以此类推

由于某种原因,它不起作用,没有 settimeout 它可以完美地工作。

据我所知,延迟后开始承诺应该没有问题,除非它可能与延迟结束后没有正确值的变量有关。如果是这样,我该如何解决这个问题,也许可以传递变量?

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

【问题讨论】:

  • @Quentin 你得更具体一些,itemsearch() 还是 promise.then() 是哪个函数?
  • @Quentin 对不起,我对 javascript 和 nodejs 还是有点陌生​​。我没有运行一次 settimeout,我为类别数组中的每个项目运行它,请参阅categories.reduce()。 return 语句是因为在 settimeout 内我试图运行 promise,return 语句是为他们准备的。
  • @Quentin 如果我错了,请纠正我,但setTimeout 接受第一个变量作为函数,第二个变量作为延迟。我不确定我传递给setTimeout的唯一功能是什么意思
  • this 之类的东西应该可以工作
  • @thefourtheye 我逐字复制了您的示例,但没有用。我很好奇,为什么解析是在延迟结束时运行,而不是在承诺完成时运行?

标签: javascript node.js promise delay settimeout


【解决方案1】:

使用async.eachSeries,您可以依次处理其中的每一个,并在每个请求完成后 1 秒执行异步回调:

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);
  }
});

【讨论】:

    猜你喜欢
    • 2020-02-07
    • 2016-12-09
    • 2017-01-25
    • 2020-07-20
    • 1970-01-01
    相关资源
    最近更新 更多