运行 函数完成并获取返回值后的代码

Run code after function completes and get returned value

假设我有一个简单的 javascript 函数:

  function someFunction(integer)
  {
    data = integer + 1;
    return data;
  }

我需要从另一个函数内部调用它并使用 returned 值:

  function anotherFunction(integer)
  {
    int_plus_one = someFunction(integer);
    //Do something with the returned data...
    int_plus_two = int_plus_one + 1;
    return int_plus_two;
  }

如何确保 anotherFunction return 的 return 仅在 someFunction 完成后才 returned?它实际上似乎可以正常使用这些非常快速的功能。但是,如果 someFunction 必须执行一些 ajax 查找,则 otherFunction 的 return 会失败。

谢谢, 史蒂夫

您不知道异步函数何时或什至是否会完成。处理这个问题的唯一方法是使用回调函数,一个在异步操作完成后执行的函数。

这是我的 "aha!" 时刻:How to return the response from an asynchronous call?

只要你的代码是同步的,上面的方法就可以了。

一旦开始引入异步部分,下面涉及回调的方法就是一种常用的方法:

function fn (v, cb) {
    doSomethingAsyncWithV(function (err, _v) {
        if(err) return cb(err);
        cb(null, _v);
    })
}

function yourFirstFn () {
    var v = 0;
    fn(v, function (err, _v) {
        // do here whatever you want with the asynchronously computed value
    });
}

承诺怎么样?考虑到这一点,就无需担心回调。这是 AngularJS.

中最酷的东西之一
var q = require('q');

var myPromise =function() {
    var deferred = q.defer();
    setTimeout(function(){  
        var output = anotherFunction(1);
        deferred.resolve(output)
    }, 10000);  // take times to compute!!! 
    return deferred.promise;
}

var objPromise = myPromise();
objPromise.then(function(outputVal){
    console.log(outputVal) ; // your output value from anotherFunction
}).catch(function(reason) {
    console.log('Error: ' + reason);
})

then 仅在 promise 已解决后执行。如果捕获到异常或错误,则执行 catch 函数。

这个怎么样?


   function someFunction(integer, callback)
   {
       data = integer + 1;
       return callback(data);
   }



  function anotherFunction(integer)
  {
     int_plus_one = someFunction(integer, function(data){
         int_plus_two = int_plus_one + 1;
         return int_plus_two;
     });
    //Do something with the returned data...

  }

您可以使用承诺:

new Promise(function someFunction(resolve, reject) {
    ajaxLib.get(url, options, function (data) {
        resolve(data);
    });
}).then(function anotherFunction(integer)
  {
    int_plus_one = integer;
    //Do something with the returned data...
    int_plus_two = int_plus_one + 1;
    return int_plus_two;
});

如果你使用 jQuery,$.ajax returns 则可用:

$.ajax(url, options).then(function processDataFromXHR(data) {
     return data.integer;
}).then(function anotherFunction(integer){
    int_plus_one = integer;
    //Do something with the returned data...
    int_plus_two = int_plus_one + 1;
    return int_plus_two;
});