angular 如何等待回调完成
angular how to wait for the callback to finish
我正在使用 ionic angular 和 cordova 插件开发移动应用程序。插件功能之一是检索数据和 return 到应用程序。我在应用程序中有一个函数可以调用插件,它将 return 给我一个字符串。但是我在插件回调之前在离子应用程序 returns 中的功能。有什么办法可以解决这个问题吗
我的离子应用程序代码试图调用插件:
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.
}
我的科尔多瓦java脚本代码:
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;
}
}
响应已打印,但函数 return 太快了。
如果有任何帮助,我将不胜感激!
通过阅读 post,我设法解决了问题。
需要使用异步和等待。
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;
我正在使用 ionic angular 和 cordova 插件开发移动应用程序。插件功能之一是检索数据和 return 到应用程序。我在应用程序中有一个函数可以调用插件,它将 return 给我一个字符串。但是我在插件回调之前在离子应用程序 returns 中的功能。有什么办法可以解决这个问题吗
我的离子应用程序代码试图调用插件:
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.
}
我的科尔多瓦java脚本代码:
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;
}
}
响应已打印,但函数 return 太快了。 如果有任何帮助,我将不胜感激!
通过阅读 post,我设法解决了问题。 需要使用异步和等待。
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;