简体   繁体   English

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

[英]Run code after function completes and get returned value

Imagine i have a simple javascript function: 想象一下,我有一个简单的javascript函数:

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

I need to call this from inside another function and use the returned value: 我需要从另一个函数内部调用此函数并使用返回值:

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

How can i ensure that the return of anotherFunction return is only returned after someFunction completes? 我如何确保anotherFunction返回的返回仅在someFunction完成之后返回? It actually seems to work ok with very fast functions like these. 实际上,使用此类非常快速的功能似乎可以正常工作。 However if someFunction has to do some ajax lookups, the return of aotherFunction fails. 但是,如果someFunction必须执行一些ajax查找,则aotherFunction的返回将失败。

Thanks, Steve 谢谢,史蒂夫

You do not know when or even if an asynchronous function will complete. 您不知道何时或什至异步功能将完成。 The only way to handle this is to use a callback function, a function that gets executed after the async operation has completed. 解决此问题的唯一方法是使用回调函数,该函数将在异步操作完成后执行。

This was my "aha!" 这是我的“啊哈!” moment: How to return the response from an asynchronous call? 瞬间: 如何从异步调用返回响应?

As far as your code is sync, the approach above is fine. 只要您的代码是同步的,上面的方法就可以了。

Once you start introducing async parts, the one below involving callbacks is a common used approach: 一旦开始引入异步部分,以下涉及回调的部分就是一种常用的方法:

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

How about promise? 诺言呢? With that in mind, there's no need to worry about callback. 考虑到这一点,无需担心回调。 It's one of the cool things in AngularJS. 这是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 is ONLY exeucted after promise has been resolved. 然后只有在诺言解决后才能执行。 If an exception or error is caught, the catch function executes. 如果捕获到异常或错误,则执行catch函数。

how about this? 这个怎么样?


   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...

  }

You could use promises: 您可以使用诺言:

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

If you use jQuery, $.ajax returns a thenable : 如果使用jQuery,则$.ajax返回thenable:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM