在循环中使用 q promise 的最佳方法是什么?在迭代到下一个之前等待链完成 [英] Whats the best approach to use q promise in a loop? Waiting for chain to complete before iterating to next

查看:43
本文介绍了在循环中使用 q promise 的最佳方法是什么?在迭代到下一个之前等待链完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下情况:

var ids = [120, 121, 122, 123, 124]

function dummyPromise(pause) {
  var deferred = Q.defer();

  setTimeout(function() {
    console.log(pause);
    deferred.resolve(pause);
  }, pause);

  return deferred.promise;
}


for(var i = 0; i < ids.length; i++) {
  dummyPromise(ids[i])
    .then(dummyPromise)
    .then(dummyPromise)
    .then(dummyPromise)
    .then(dummyPromise)
    .done(function(){
      console.log('done')
    })
}

我想在迭代到下一个之前等待链完成.解决这个问题的最佳方法是什么?

I want to wait for chains to complete before iterating to next. Whats the best way to approach this?

推荐答案

在这些示例中,我使用标准的 Promise.如果你需要使用(很棒的)Q 库,你可以通过用 Q.fcall(fn, arg) 代替 Promise.resolve(arg).then(fn) 或使用 Q() 而不是 Promise.resolve().

In these examples I use standard Promises. If you need to use (the awesome) Q library, you can make it shorter by substituting Q.fcall(fn, arg) in places of Promise.resolve(arg).then(fn) or using Q() instead of Promise.resolve().

var q = Promise.resolve();

for (var i = 0; i < 10; i++) {
  (function(item, index){
    q = q.then(function() {
      return // do async stuff here
    });
  })(ids[i], i);
}

q.then(function() {
  // all iterations finished
});

使用数组

function forEachAsync(arr, fn) {
  var index = 0;
  function next() {
    if (index < arr.length) {
      var current = index++;
      return Promise.resolve().then(function() {
        return fn(arr[current], current, arr);
      }).then(next);
    }
  }
  return Promise.resolve().then(next);
}

...

forEachAsync(ids, function(item, idx) { ... }).then(...)

使用可迭代对象

function forOfAsync(iterable, fn) {
  var iterator = iterable[Symbol.iterator]();
  function next() {
    var iteration = iterator.next();
    if (iteration.done) {
      return iteration.value;
    } else {
      return Promise.resolve(iteration.value).then(fn).then(next);
    }
  }
  return Promise.resolve().then(next);
}

forOfAsync(ids, function(id) { ... }).then(...)

使用 async-await

for (let id of ids) {
  await doSomeAsyncStuffWithId(id);
}

这篇关于在循环中使用 q promise 的最佳方法是什么?在迭代到下一个之前等待链完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆