Davide Maestroni created CB-2963:
------------------------------------

             Summary: Javascript callback functions are not executed in the 
correct order
                 Key: CB-2963
                 URL: https://issues.apache.org/jira/browse/CB-2963
             Project: Apache Cordova
          Issue Type: Bug
          Components: Android
    Affects Versions: 2.5.0
            Reporter: Davide Maestroni
            Assignee: Joe Bowser
            Priority: Critical


I created an application which sends asynchronous notifications from the native 
to the Javascript side. I noticed that in some cases the Javascript code of the 
callbacks is not executed in the expected order.
Let me show an example:
# a native event trigger a notification to the Javascript side where a callback 
function (callback1 - part 1) gets correctly called
# in the while, on the native side, a different notification is triggered
# inside the Javascript code of the first callback the cordova.exec() API is 
issued
# at this point the Javascript code of the second callback (callback2) is 
executed sequentially on the same thread
# when the second callback completes, the final part of the code in the first 
callback (callback1 - part 2) is executed

So that, if the callback functions are defined as below:

{noformat}
function callback1() {
    <callback1 - part 1>
    cordova.exec(...);
    <callback1 - part 2>
}

function callback2() {
    <callback2>
}
{noformat}

the Javascript code gets executed in the following order:

{noformat}
<callback1 - part 1>
cordova.exec(...);
<callback2>
<callback1 - part 2>
{noformat}

which is not the expected behavior.

I believe the problem is related to the following lines of code in the 
_cordova.android.js_ file:

{noformat}
        var messages = nativeApiProvider.get().exec(service, action, 
callbackId, argsJson);
        androidExec.processMessages(messages);
{noformat}

which get called if _jsToNativeBridgeMode == jsToNativeModes.JS_OBJECT_.
That causes enqueued messages to get executed sequentially before the execution 
of the first callback is complete.
An easy fix would be to change the above code into:

{noformat}
        var messages = nativeApiProvider.get().exec(service, action, 
callbackId, argsJson);
        setTimeout(function() {
                androidExec.processMessages(messages);
        }, 0);
{noformat}

so that the enqueued messages are processed in the next Javascript loop.


--
This message is automatically generated by JIRA.
If you think it was sent incorrectly, please contact your JIRA administrators
For more information on JIRA, see: http://www.atlassian.com/software/jira

Reply via email to