问题
My problem is quite simple but I can't find anything online. I am finishing development of a phone app, and I am having some issues with Cordova because of the not-synchronous execution. As it is right now, I have to do something like this:
var finishedFl = 0;
cordova.exec(
function(info) {
.... [Function goes here]
finishedFl = 1;
},
function (info) {
alert('Error');
},
'Smapps', 'getInfo', []);
While(finishedFl != 1){
wait;
}
anotherFunction();
I find this way of programming extremely troubling and obviously not that good. So the question is: Is there any way of making Cordova execution synchronous?
回答1:
The exec method sends a message to the OS via the MesageQueue and performs and action usually in a different thread (it doesn't run on the UI thread). When the native call is finished message is send to JS layer and successCallaback is called. In case of error another message is sent and errorCallaback fires. If you are the creator of the plugin you can call the runOnUIThread(new Runnable(){....}) method (at least in Android) to perform something on the UI thread, but it's not recommended, because of blocking the UI.
If you don't like the idea of callback leading to "callback hell". You can wrap the callbacks in promises. So you could do something like this cordova.wrappedExec().then(successCallback).then(doSomethingElse); Take a look here https://github.com/stackp/promisejs
来源:https://stackoverflow.com/questions/24064082/how-to-make-cordova-synchronous