Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/390.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何从延迟返回值?_Javascript_Dojo_Callback_Deferred - Fatal编程技术网

Javascript 如何从延迟返回值?

Javascript 如何从延迟返回值?,javascript,dojo,callback,deferred,Javascript,Dojo,Callback,Deferred,我正在调用一个方法,该方法在延迟中具有一些逻辑,当该逻辑完成时,我希望将该值返回给被调用方。见下文: //Callee.js var myAssistant = new Assistant(); console.log(myAssistant.whatIsTheValue()); //Assistant.js whatIsTheValue : function(someArg) { var deferred = someService.getSomething(); defer

我正在调用一个方法,该方法在延迟中具有一些逻辑,当该逻辑完成时,我希望将该值返回给被调用方。见下文:

//Callee.js
var myAssistant = new Assistant();
console.log(myAssistant.whatIsTheValue());



//Assistant.js
whatIsTheValue : function(someArg) {
   var deferred = someService.getSomething();
   deferred.then(lang.hitch(this, this._getTheValue));

   //In theory, I want to return whatever this._getTheValue returns, how can I do that?!
}

_getTheValue() {
   ...
   ...
   return xyz;
}

延迟是异步操作。因此,您不能以正常方式从它们返回变量,因为它们在当前函数上下文完成之前不会执行

如果你想用这个值做更多的事情,你需要在另一个回调中这样做(即链接then语句)

延迟的要点是为回调提供顺序操作。因此,您可以链接它们以实现您想要的结果。如果您需要在当前执行上下文中获得结果,那么您必须找到一种同步(而不是延迟)方法来做您想要做的事情

像这样的

//Assistant.js
whatIsTheValue : function(someArg) {
   var deferred = someService.getSomething();
   var next = deferred.then(lang.hitch(this, this._getTheValue));
   next.then(/*insert next function here*/);
}

您需要了解,使用延迟的lang.hitch在值运行完成之前是不会执行的。因此,您将不得不将处理该值的逻辑放入一个新函数中,并将其用作延迟函数的额外回调,而不是将该值返回给任何名为whatisthevalue的函数。这可能需要对您的程序进行一些重组

我不知道你的
lang.hitch
是做什么的,但解决方案应该是这样的:

Assistant.prototype.whatIsTheValue = function(someArg) {
    var deferred = someService.getSomething();
    return deferred.then(lang.hitch(this, this._getTheValue));
//  ^^^^^^
};

var myAssistant = new Assistant();
myAssistant.whatIsTheValue().then(console.log); // use console.log.bind(console) in Chrome
//                           ^^^^ - it is a promise you return

改用JQuery的
$when

范例

// assuming both getData and getLocation return their respective Promise
var combinedPromise = $.when(getData(), getLocation())

// function will be called when both getData and getLocation resolve
combinePromise.done(function(data,location){
  alert("We got data: " + dataResult + " and location: " + location);
}); 

你似乎不理解尊重。我明白了基本概念。我只是没有看到这个问题的解决方法。同样没有理由问两次同样的问题:你会注意到你两次都得到了基本相同的答案。实际上,我想返回一个值,一旦我们有了一个值,你就必须使用回调,并在回调中做任何你想做的事情。无法立即将值返回到该函数contecxt中,因为您正在进行异步调用,并且在事件发生且当前函数上下文完成之前,它不会执行。