2013-01-10 42 views
3

我正在調用一個延遲的邏輯的方法,當這個邏輯完成時,我想把值返回給被調用者。見下:如何從延遲中返回值?

//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; 
} 
+0

你似乎並沒有理解Deferreds。 – Bergi

+0

我明白了基本概念。我只是沒有看到這個問題的解決方法。 – antonpug

+0

也沒有理由兩次提出相同的問題:http://stackoverflow.com/questions/14260686/how-to-get-a-deferred-handler-to-return-a-value-to-the-calling功能?rq = 1 你會發現你兩次獲得基本相同的答案。 –

回答

1

我不知道你的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 
0

延期是異步操作。因此,您不能以正常方式從它們返回變量,因爲它們只有在當前函數上下文完成之後纔會執行。

如果你想要做更多與價值,你需要在另一個回調的協議來執行(IE鏈接當時的陳述。)

deferreds的一點是要回調提供順序操作。所以你可以鏈接他們來實現你想要的結果。如果你需要結果在當前的執行上下文中可用,你將不得不找到一個同步(而不是延遲)的方法來做你想做的事情。

因此,像這樣

//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完成操作後。因此,不必將值返回到任何稱爲whatisthevalue的函數中,而必須將處理該值的邏輯放入一個新函數中,並將其用作延遲的額外回調函數。這可能需要對您的程序進行一些重組。

+0

沒錯。所以我怎麼能實施一個解決方法? – antonpug

+0

實際上,我想要返回一個值,一旦我們的值爲 – antonpug

+0

,您將必須使用回調函數,並在回調函數中執行任何您想要執行的操作。沒有辦法立即將值返回到該函數contecxt中,因爲您正在進行異步調用,並且在事件發生並且當前的函數上下文已經完成之前它不會執行。 –

1

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

http://www.html5rocks.com/en/tutorials/async/deferred/