Javascript 函数完成后运行代码并获取返回值
假设我有一个简单的javascript函数:Javascript 函数完成后运行代码并获取返回值,javascript,callback,Javascript,Callback,假设我有一个简单的javascript函数: function someFunction(integer) { data = integer + 1; return data; } 我需要从另一个函数内部调用此函数并使用返回值: function anotherFunction(integer) { int_plus_one = someFunction(integer); //Do something with the returned d
function someFunction(integer)
{
data = integer + 1;
return data;
}
我需要从另一个函数内部调用此函数并使用返回值:
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;
}
如何确保仅在某个函数完成后才返回另一个函数的返回?实际上,它似乎可以与这些非常快速的函数一起工作。但是,如果某个函数必须执行一些ajax查找,那么aotherFunction的返回将失败
谢谢,
Steve您不知道异步功能何时或是否会完成。处理此问题的唯一方法是使用回调函数,该函数在异步操作完成后执行
这是我的“啊哈!”时刻:就您的代码同步而言,上述方法很好 一旦开始引入异步部分,下面涉及回调的部分就是常用的方法:
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);
})
只有在承诺得到解决后才可执行。如果捕获到异常或错误,则执行catch函数。这如何
你可以使用承诺:
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
将返回一个表:
$.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;
});
不能返回异步操作。您必须进行异步调用,然后对回调中接收到的数据执行所有必须执行的操作。谢谢Daniel_L-我如何在示例中做到这一点?我认为我需要使用回调-但我似乎不知道如何做到这一点,并且仍然使用从某个函数返回?在这个示例中没有异步函数。请不要使用延迟对象,因为它(正确地)被认为是反模式的,这本身并没有错,但我认为从“我不知道如何使用异步函数”跳到“use AngularJS Promissions”是一个巨大的飞跃。感谢您提供的pointer gwg-优秀的文章,它解释了我需要做什么。代码现在可以按要求工作了!
$.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;
});