角度如何等待回调完成



我正在开发一个移动应用程序,使用离子角和cordova插件。插件功能之一是检索数据并返回到应用程序。我在应用程序中有一个函数来调用插件,它将返回一个字符串。但是,我在 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;
}
}

已打印响应,但函数返回太快。 我将不胜感激任何帮助!

通过阅读这篇文章,我设法解决了这个问题。 需要使用异步和等待。

const test = await cordova.plugins.MationPlugin.getGroupAllInfo(data, (response) => {
console.log('response:' + response);
this.result = response;
}, (error) => {
console.log('error: ' + error);
});
console.log('print variable test: ' + this.result);
return this.result;

最新更新