2017-02-28 111 views
1

我有這樣的代碼:如何在自己的回調函數中使用函數的返回值?

$('#from_country').change(function() { 
    var selected_from = $(this).find('option:selected'); 
    var country = roaming_prices_from(selected_from.val(), function() { 
     console.log(country); 
    }); 

我如何使用它自己的回調函數內的roaming_prices_from的返回值?

+0

將值作爲參數傳遞給回調函數是'roaming_prices_from'的責任。你必須改變這個函數,或者不要使用這個函數作爲回調函數(例如'callback(roaming_prices_from(selected_from.val()));') –

+0

爲什麼你不能在調用它時將'country'傳遞給回調方法從'roaming_prices_from'方法? – Satpal

+0

like like:'var country = roaming_prices_from(selected_from.val(),function(country){ console.log(country); });'?這dosnt似乎工作,但如果這是正確的。那我可能會在別的地方犯錯。 –

回答

2

通過傳遞你的函數的返回值作爲回調參數,

$('#from_country').change(function() { 
    var selected_from = $(this).find('option:selected'); 
    var country = roaming_prices_from(selected_from.val(), function (xCountry) { 
     console.log(xCountry); 
    }); 
}); 

但要做到這一點,你必須通過你的roaming_prices_from函數中的值

我們將假設功能roaming_prices_from會如下所示: -

function roaming_prices_from(value, callback) { 
    ..... 
    callback(returnedValue); 
    ..... 
    return returnedValue; 
} 
0

您需要假設roaming_prices_from將與國家v即功能將有Promise.resolve(country),這意味着你的回調(打印出來的國家)將會收到country作爲參數