0

I am developing a mobile app using ionic angular with cordova plugin. One of the plugin function is to retrieve data and return to the app. I have a function in the app to call the plugin which will return me a string. However my function in the ionic app returns before the plugin's callback. Is there any way to solve this problem.

My ionic app code trying to call plugin:

   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.

   }

my cordova javascript code:

 var MationPlugin = {
    getGroupAllInfo: function(arg0, cb,error) {
        console.log("plugin js: getGroupAllInfo is called");
      exec(cb, error, PLUGIN_NAME, 'getGroupAllInfo', [arg0]);
      }
}

my java codes:

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

the response is printed but the function returns too fast. I would appreciate any help!

zifan yan
  • 125
  • 2
  • 11
  • Does this answer your question? [How do I return the response from an Observable/http/async call in angular?](https://stackoverflow.com/questions/43055706/how-do-i-return-the-response-from-an-observable-http-async-call-in-angular) – R. Richards Feb 09 '20 at 12:11
  • yes it solved my problem! – zifan yan Feb 09 '20 at 13:17

1 Answers1

1

By reading the post, i managed to solve the problem. need to use async and 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;
zifan yan
  • 125
  • 2
  • 11