如何使Cordova同步 [英] How to make Cordova synchronous

查看:203
本文介绍了如何使Cordova同步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题很简单但我在网上找不到任何东西。我正在完成手机应用程序的开发,由于非同步执行,我在Cordova遇到了一些问题。就像现在一样,我必须做这样的事情:

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();

我觉得这种编程方式非常令人不安,显然不是那么好。所以问题是:有没有办法使Cordova执行同步?

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?

推荐答案

exec方法通过OS向OS发送消息MesageQueue并且通常在不同的线程中执行和操作(它不在UI线程上运行)。当本机调用完成时,将消息发送到JS层并调用successCallaback。如果出现错误,则会发送另一条消息并触发errorCallaback。如果你是插件的创建者,你可以调用runOnUIThread(新的Runnable(){....})方法(至少在Android中)来在UI线程上执行某些操作,但是不建议这样做,因为阻止了UI 。

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.

如果你不喜欢回调导致回调地狱的想法。您可以将回调包装在promises中。所以你可以做这样的事情
cordova.wrappedExec()。然后(successCallback).then(doSomethingElse);
在这里查看 https://github.com/stackp/promisejs

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

这篇关于如何使Cordova同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆