簡體   English   中英

angular 如何等待回調完成

[英]angular how to wait for the callback to finish

我正在使用帶有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;
        }
}

響應被打印,但函數返回太快。 我將不勝感激任何幫助!

通過閱讀帖子,我設法解決了問題。 需要使用異步和等待。

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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM