1

I have to make an async call to a 3rd party API and I want the code execution to wait for the response.

async function getOrderData(orderId) {
  return new Promise(function (resolve, reject) {
    var service = new APIservice();
    service.GetOrderData(oid, function (event) {
      if (event && event.hasErrors() == false) {
        resolve(event.result);
      } else {
        reject(null);
      }
    });
  });
}

var order = getOrderData(orderId);
//from here the code should only resume once the var order is defined with whatever's returned from the api

This is the top level code (not async) so I cannot use await.

EDIT: Answering some suggestions:

this.$onInit = function () {
    this.order = "wrong value";
    getOrderData(orderId).then(order => {
        this.order = "correct value";
    });
};

this function will end with "test" being "wrong value". This is what I am trying to avoid.

Jaime Oliveira
  • 751
  • 1
  • 5
  • 13
  • 1
    Can you not wrap that code in an async function and await the response? We may need more context here. – Drew Reese Jun 05 '19 at 15:36
  • What is `GetOrdersById`? I don't see that in your question at all. If you meant `getOrderData` being `async` that doesn't matter, you want the function the code snippet posted is running in to be `async` so you can `await` the return response of `getOrderData`, as others have posted solutions of. – Drew Reese Jun 05 '19 at 15:54
  • Yeah, I tried that. "GetOrderData" is an async function (sorry for the typo) – Jaime Oliveira Jun 05 '19 at 15:55
  • Possible duplicate of [How can I use async/await at the top level?](https://stackoverflow.com/questions/46515764/how-can-i-use-async-await-at-the-top-level) – ponury-kostek Jun 05 '19 at 15:58

2 Answers2

3

You can await the Promise returned by getOrderData().

However, in order to use await you need to wrap your call to getOrderData in an async function (there is no such thing as top-level await at the moment - it may one day be a thing however. At present, it can only be used when inside an async function):

// getOrderData function initializaion...

(async _ => {
  var order = await getOrderData(orderId); // wait to recieve data before proceeding
  // You can now write code wih `order`
})().catch(err => {
  console.error(err);
});

Alternatively, you can write your code in a .then callback (which await is simply just syntactic sugar for) from the returned Promise of getOrderData() like so:

// getOrderData function initializaion...

getOrderData(orderId).then(order => {
  // write code in here which relies on `order`
}).catch(err => {
  console.error(err);
});;
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
  • this.$onInit = function () { this.test = "wrong value"; getOrderData(orderId).then(order => { this.test = "correct value"; }); }; – Jaime Oliveira Jun 05 '19 at 16:25
0

you need something like this:

async function the_whole_thing() {
  async function the_api_wrapper() {
    return new Promise((resolve, reject) => {
      setTimeout(() => resolve('joe!'), 10);
    });
  }
  
  let result = await the_api_wrapper();
  console.log(result);
}

the_whole_thing();

Note #1: I just swapped out the API you are calling with setTimeout, as it is also a function that takes a callback (similar to your case) and it also ensures stuff happen asynchronously.

Note #2: note that the async/await syntax can only be used in the body of another async function, so thats why I wrapped the whole thing, well, in the_whole_thing.

  • Sorry, I am missing the point. If I call "the_whole_thing" in the main thread will I not get the same result (thread ending before my var is defined)? – Jaime Oliveira Jun 05 '19 at 15:46
  • you will get the same result. but you cannot get the value in the main thread, at least not with a simple variable assignment. basically `x = f()` when `f` is an async function will not cause x to be the result of `f` but a `Promise` that can be used to fetch the result of `f` in an async manner. you can work around that by doing `x = await f()`, however you will not be able to do that in your main thread (or in the body of any function that is not async itself). perhaps [this pen](https://codepen.io/lorean_victor/pen/WBBRvq) can help illustrate that difference better. – Eugene Ghanizadeh Khoub Jun 05 '19 at 22:28