2013-07-25 27 views
0

我在Flash這個功能:布爾是Flash真實的,但假在Javascript

public function checkFile(file:String):Boolean{ 
       var b:Boolean; 
       var responder:Responder = new Responder(function(reply:Boolean):void{ 
        b=reply; 
        msg("vid_"+file+".flv "+ "exists? " + reply); 
        setState("ready"); 
        status = "ready"; 
       }, 
        function(res:Object):void{ 
         trace("checkFile call failed"); 
        }); 
       mync.call("checkFile",responder,"vid_"+file); 
       return b; 
      } 

我可以證實,reply變量是真實的,但return b結束了假:

這是JavaScript的我用來調用Flash功能:

function checkFile(){ 
    alert(thisMovie("vidRecorder").checkFile(currentVid));   
} 

這開闢了一個消息框,說false,而Flash文件顯示true

發生了什麼事?我該如何修復它,以便我的函數返回與reply相同的值?

+1

發生什麼事是**異步操作** – Pointy

+0

@Pointy哦不!這聽起來不祥,特別是因爲你把它放在粗體中。讓我看看。 – Houseman

+1

異步和回調的概念在[this thread]中得到了很好的解釋(http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call)。 –

回答

1

發生這種情況是因爲響應者中的匿名函數是異步執行的。

當你的checkFile()函數返回值b仍然是false。最終,您的匿名函數將被執行並且b被設置爲true ...但在這種情況下已經太晚了,因爲您的checkFile()函數已經返回false

要解決這個問題,你可以考慮在一個稍微不同的方式這樣做:

當執行你的匿名函數,把它與異步響應召喚出來的JavaScript。事情是這樣的:

public function checkFile(file:String):void { 
    var responder:Responder = new Responder(function(reply:Boolean):void{ 
     msg("vid_"+file+".flv "+ "exists? " + reply); 
     setState("ready"); 
     status = "ready"; 
     ExternalInterface.call('someJavascriptFunction', reply); 
    }, 
    function(res:Object):void{ 
     trace("checkFile call failed"); 
    }); 
    mync.call("checkFile",responder,"vid_"+file); 
    // note we no longer return a value here 
} 

在上面的代碼中,我們調用一個新的JavaScript功能,並提供它的異步操作的結果。

相關問題