我正在使用带有Cordova插件的ionic angular开发一个移动应用程序。插件功能之一是检索数据并返回到应用程序。我在应用程序中有一个函数来调用插件,它将返回一个字符串。但是,我在ionic应用程序中的功能在插件的回调之前返回。有什么办法可以解决这个问题。
我的离子应用程序代码试图调用插件:
public getinfo(): string {
const data = {some json};
cordova.plugins.MationPlugin.getGroupAllInfo(data, (response) => {
console.log('response:' + response); //i can print this part
this.result = response;
isDone = true;
}, (error) => {
console.log('error: ' + error);
});
console.log('getAllGroups: ' + this.result); //shows result is undefined
return this.result; // it returns a null here.
}
我的科尔多瓦javascript代码:
var MationPlugin = {
getGroupAllInfo: function(arg0, cb,error) {
console.log("plugin js: getGroupAllInfo is called");
exec(cb, error, PLUGIN_NAME, 'getGroupAllInfo', [arg0]);
}
}
我的Java代码:
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException{
if(action.equals("getGroupAllInfo")){
this.getGroupAllInfo(callbackContext);
try{
Thread.sleep(100);
}catch(InterruptedException e){
e.printStackTrace();
}
callbackContext.success(this.allInfo.getString("data"));
return true;
}
}
打印响应,但函数返回太快。我将不胜感激!
通过阅读帖子,我设法解决了这个问题。需要使用异步并等待。