2012-12-21 194 views
3

下面顯示的是js代碼,它調用了iOS和Android中的原生函數,這個函數是從另一個js方法調用的。由於js調用這個函數是異步的,我們不能返回iOS中的任何值,但在Android中,我們可以返回值,而不會有任何問題。在iOS控件中,dosent會等待,直到我得到響應。實際上,我們不會修改此函數調用,否則我們可以從調用者函數傳遞迴調方法。請幫我解決這個問題iOS返回異步javascript調用值

VestaPhoneBridge.IsAvailable = function(featureName) 
{ 
    if(isAndroid()) { 
    if(typeof VestaJavascriptInterface !== 'undefined') 
    { 
     return VestaJavascriptInterface.isAvailable(featureName); 
    } 
    return false; 
    } 
    else {     
    bridge.callHandler('initiateIsAvailableFunction',featureName,function(response) { 
     return response; 
    }) 
    }  
}; 

回答

0

我假設你在談論這一行。

bridge.callHandler('initiateIsAvailableFunction',featureName,function(response) { 
    return response; 
}) 

問題很可能是您的return。只要異步請求完成,就會調用您作爲回調傳遞的匿名函數。這意味着它將被callHandler代碼路徑中的內容調用。

您的函數然後返回到該函數,而不是VestaPhoneBridge.IsAvailable函數。您的回調應設置值,並執行更改而不是返回值。

function Foo(callback) { 
    callback(); // 42 is returned here, but not assigned to anything! 
} 

function Bar() { 
    var baz = Foo(function() { 
    // You want to return 42. But here you are in a totally different function 
    // scope! You are in the anonymous function's scope, not Bar, so you are not 
    // returning anything to the caller of Bar(). 
    return 42; 
    } 
    alert(baz); // Foo doesn't return anything, so this is undefined! 
} 

alert(Bar()); // This is also undefined, nothing was returned. 
+0

唯美您好,感謝您的回答。你的意思是使用回調函數將是解決這個問題的唯一方法嗎? – user1878200

+0

@ user1878200 - 我添加了一個例子,希望它能幫助你理解你爲什麼破壞了。 – Aesthete