javascript – 在循环内进行异步调用,直到找到值

我正在尝试在循环内对异步API进行多次调用,直到返回我想要的值(在本例中为true).问题是我不希望在找到该值之后继续循环,并且我不想在循环之后执行这些行而没有从它返回的值…但到目前为止我无法使其工作.我觉得我在这里做错了,但“我无法全面了解”.

function isSelected(element, callback) {
  // This is a little bit confusing for me...can I just get the value from
  // getDataAsync without using isSelected function?
  Office.select(element).getDataAsync(function (asyncResult) {
    var result = true;

    // some logic here that may change 'result'
    callback(result);
  });
}

function delete(elements) {
  var index = -1;

  for (var i = 0, (i < elements.length) && (index < 0); i++) {
    isSelected(elements[i], function(result) {
      if (result) { index = i; }; // ...and I don't want to keep "looping"
    });
  }
  // I want to execute these lines after the for-loop is done
  // ...do something with the "correct" index value
}

最佳答案 你试过
Kriskowal’s Q吗?有一个很好的函数叫Q#allSettled:

Q.allSettled(promises)
.then(function (results) {
    results.forEach(function (result) {
        if (result.state === "fulfilled") {
            var value = result.value;
        } else {
            var reason = result.reason;
        }
    });
});

所以基本上这就是它在你的情况下如何工作:

var promises = [];

for(/* conditions */) {
  promises.push(/* async call which returns a promise */);
}

Q.allSettled(promises).then(function(results) {
    results.forEach(function (result) {
        var value;

        if (result.state === "fulfilled") {
            value = result.value;

            // do something with "value"
        }
    });
});

allSettled只是确保无论promise是否成功都将执行then,并且您可以检查从异步调用中检索的对象的值.

点赞