如何保证在函数返回之前保存异步返回值?

时间:2014-07-10 18:31:51

标签: javascript asynchronous

据我了解,下面代码中的100个asyncFunctions在func返回true之后才会执行,此时对i的引用将无效。我猜这个代码中的任何内容都不会按预期工作。

Psedo示例代码:

function func(){
  var needToKnow = []
  for i = 1 to 100 {
    needToKnow[i] = asyncFunction( i )
  }
  //Do some work on needToKnow[i]
  return true
}

Javascript如何做这样的事情?

2 个答案:

答案 0 :(得分:2)

使用callbacks

function func(callback) {
    var needToKnow = [],
        max = 100;

    for (var i = 0; i < max; i++) {
        asyncFunction(i, function (result) {
            needToKnow.push(result);

            if (needToKnow.length == max) { // or something that let you know that its finished
                callback(needToKnow);
            }
        });
    }
}

function asyncFunction(i, callback) {
    setTimeout(function () {
        callback({ index: i });
    }, 1000); // Im an async func!
}

并以这种方式使用它:

func(function (result) {
    console.log(result);
});

小心,不要进入callback hell

答案 1 :(得分:1)

以下是使用Q Promise库的示例:

function functionThatCouldThrowError(i){
  //It doesn't, but just to give an idea of error propagation.
  return { index: i };
}

function asyncFunction(i) {
  var deferred = Q.defer();
    setTimeout(function () {
      try{
        var data = functionThatCouldThrowError(i);
        deferred.resolve(data);
      } catch (error) {
        deferred.reject({ index: i, error: error });
      }
    }, 1000);
    return deferred.promise;
}

function doAll() {
  var needToKnow = []
  for (var i = 0; i < 100; i++) {
    needToKnow[i] = asyncFunction( i );
  }
  return Q.all(needToKnow);
}

doAll().then(function(arg) {
  //arg contains all 100 elements
  alert("All done");
})

更新:展开示例以演示如何处理错误。 Plunker:http://plnkr.co/edit/djWpTKxgvzK2HmkVwvTy?p=preview