非同步回呼:傳回值
由於非同步回呼函數的非阻塞性質,從非同步回調函數傳回值可能是一個挑戰。以下是問題的細分和解決方案:
在提供的範例中:
function foo(address) { // Google Maps stuff geocoder.geocode({'address': address}, function(results, status) { // Unable to return results[0].geometry.location synchronously }); }
在非同步地理編碼回調內,無法同步擷取您要傳回的值。嘗試這樣做將導致未定義的值。
解:回呼結果
要取得該值,您可以將回調函數傳遞給foo ,該函數將接收結果:
function foo(address, callback) { geocoder.geocode({'address': address}, function(results, status) { callback(results[0].geometry.location); }); }
在foo的回調中,您可以存取該位置value:
foo("address", function(location) { alert(location); // Result obtained here });
非同步函數鏈
如果非同步呼叫嵌套在另一個函數中,則該函數也必須是異步的才能取得回傳值。對於複雜的場景,可以考慮使用像 Q 這樣的 Promise 程式庫來有效地管理非同步操作。
以上是如何從 JavaScript 中的非同步回呼函數傳回值?的詳細內容。更多資訊請關注PHP中文網其他相關文章!