【问题标题】:angular how to wait for the callback to finish角度如何等待回调完成
【发布时间】:2020-02-09 11:49:14
【问题描述】:

我正在使用带有 cordova 插件的 ionic angular 开发一个移动应用程序。插件功能之一是检索数据并返回到应用程序。我在应用程序中有一个函数来调用插件,它将返回一个字符串。但是,我在 ionic 应用程序中的函数在插件回调之前返回。有什么办法可以解决这个问题。

我的 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;
        }
}

打印响应但函数返回太快。 我将不胜感激!

【问题讨论】:

标签: angular ionic-framework callback


【解决方案1】:

通过阅读帖子,我设法解决了问题。 需要使用 async 和 await。

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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-10
    • 2019-11-06
    • 1970-01-01
    • 2016-03-09
    • 2016-02-17
    • 2021-03-05
    • 2018-02-28
    • 2021-11-13
    相关资源
    最近更新 更多