How to make Cordova synchronous

自作多情 提交于 2020-01-01 12:01:36

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!