2016-08-11 56 views
0

我不知道如何設置一個變量值(例如ajax調用的響應)使用承諾。如何設置變量值與承諾

我有,例如:

something.value = getVariable('id'); // { id : 'Adam Smith' } 

其中

getVariable(id) { 
    return $.ajax({ 
    //... 
}).done(function(response) { 
    //... getVariable return response 
}).fail(function(response) { 
    //... getVariable return something_else 
}); 
    // ... 

的getVariable應承諾變爲AJAX(或任何其他異步)響應值做一次()。

+0

你不能這樣做,因爲承諾不會使異步代碼同步 –

+0

好吧,所以唯一的辦法是將值分配給回調權? – Daniele

+0

如果我理解你的意思,那麼是的 –

回答

1

你不能直接設置變量的方式,你試圖做到這一點。由於您的操作是異步的,因此唯一可以可靠地使用異步操作結果的地方位於承諾處理程序的內部,例如.done().then()。因此,將結果設置爲某個變量,然後期望在其他代碼中使用該變量通常無法正常工作。這通常會導致計時問題。

相反,您必須學會使用異步結果進行編程,其中您實際上在promise處理回調中使用了變量。你不存儲它,然後期望在其他代碼中使用它。

function getVariable(id) { 
    return $.ajax({...}); 
}); 

getVariable(...).then(function(response) { 
    // process result here 
    // don't just store it somewhere and expect other code to use that stored 
    // value. Instead, you use the result here and put whatever code 
    // needs that value in here. 
}, function(err) { 
    // handle error here 
});