PlayHardGoPro
PlayHardGoPro

Reputation: 2923

Async/Await function not waiting for promise to end

let myObject = ( () => {

  let run = async() => {
    foo = new genericFunction();
    status = await foo.myFunction();
  }

})();

Another FIle.js

let genericFunction = function() {


  this.getData = async () => {
    $.getJSON("path/to/file.json", function (data) {
      console.log("Apple", data.name);
      return data.name;
    }).fail(function(jqxhr, textStatus, error){
      console.log("Loading Error :: ", error);
    )};

  }


  this.myFunction = async () => {
    let data = this.getData();
    console.log('DATAA:::', data); //This should be the first output
  }

}

The problem is: status is always = undefined because somehow it returns before getJSON executes and I don't know why.

Upvotes: 0

Views: 77

Answers (2)

Andy
Andy

Reputation: 63514

Here's a simplified example using your code but with a couple of changes:

1) Uses a class

2) You're not returning anything from myFunction so there's no reason to assign something to status - just call the function.

3) getData doesn't need an async keyword, and you need to return the promise (in this example I mocked up a AJAX call that returns data after a second) from the function for it to work.

4) You do need to await for the promise to return in myFunction. You have async there, you just need to add the await keyword too.

class GenericFunction {

  getData() {
    return new Promise(resolve => {
      setTimeout(() => resolve('Hello World'), 2000);
    });
  }

  async myFunction() {
    let data = await this.getData();
    console.log('DATAA:::', data);
  }

}

(async () => {
  const foo = new GenericFunction();
  foo.myFunction();
})();

Upvotes: 1

Dabbas
Dabbas

Reputation: 3230

Another FIle.js should be like:

let genericFunction = function() {


  this.getData = async () => {
    var result = await $.getJSON("path/to/file.json", function (data) {
      console.log("Apple", data.name);
      return data.name;
    }).catch(function(jqxhr, textStatus, error){
      console.log("Loading Error :: ", error);
    )};

    return result;
  }


  this.myFunction = async () => {
    let data = this.getData();
    console.log('DATAA:::', data); //This should be the first output
  }

}

Upvotes: 1

Related Questions