Issue in handling async function called by another function

async arrow function
async/await vs promises
async/await error handling
await javascript
nodejs async/await
async call
await is only valid in async function
nodejs async function

Briefly , I have 2 functions A,B

A is async function , takes time to request something then be ready with response to return

B take output from A

here's my codes

async function A()
{
    axios.get('API_ENDPOINT_URL').then(async function (rates) {
        return new Promise((resolve , reject) => {
            resolve(rates.data.data);
        });
    });
}

async function B(id)
{
    var results = A();
    console.log(results); // this output Promise { undefined }
}

how to solve this issue ?

 var results = await A();

just await the execution of A. And also fix A itself, it is completely missusing promises:

 async function A() {
  const rates = await axios.get('API_ENDPOINT_URL')
  return  rates.data.data;
}

Javascript, makes JavaScript wait until that promise settles and returns its result. The BuildMenu () function is called from another block of code and it calls the CreateMenuData () which makes a request to a service which return some data. The problem is that since it is an async call to the service when the data variable is being used it is undefined.

Your function A returns a promise, so you can either use await A() or A().then(results => console.log(results))

await is only valid in async function, works only inside async functions let value = await promise ; can do other jobs in the meantime: execute other scripts, handle events, etc. We'll need to replace .then calls with await . If you have suggestions what to improve - please submit a GitHub issue or a pull request instead of commenting. This refers to the situation where you do not want to await an asynchronous method and you're not particularly concerned about when it finishes. In that case, consider, at the very least, adding a ContinueWith with TaskContinuationOptions.OnlyOnFaulted where you can log any exceptions that may arise.

You have call .then on a promise, like this:

function A()
{
  return new Promise((resolve , reject) => {
      resolve("test");
  });
}

function B()
{
  A().then(result=>console.log(result));
}

B();

Async/await, A callback is nothing special but a function that is executed at some later time. Problems arise when we want to do multiple async operations. This is affectionately called as Callback Hell or Pyramid of Doom due Error handling is complicated and often leads to bad code. Here's another example — Thanks @olragon, I just tried moving the lookupAgain() call to the top var dnsQueue = async.queue(function(domain, lookupAgain) {lookupAgain(); But it still seems to be running the drain function right away.

There's actually no particular reason you need async or await here. You can also just return a value from the .then() handler which will work in any environment that supports axios (doesn't require async/await support):

function A() {
    return axios.get('API_ENDPOINT_URL').then(function (rates) {
        return rates.data.data;
    });
}

// usage
A().then(result => {
   console.log(result);
}).catch(err => {
   console.log(err);
});

In case you didn't realize, both this version and the version above using await return the same thing - a promise that resolves to rates.data.data or rejects with an axios error.

Returning a value from a .then() handler changes the resolved value of the promise chain to the value you returned.

Unless that value is also a promise in which case that promise gets added to the chain and the resolved value of the chain becomes the resolved value of that new promise that you returned.

As we can see from the above result, each function call and… For example, handling of AJAX request should be done on a different Let's add asynchronous nature to our earlier example and see the problem with it. If instead of just invoking fn() here you instead check to see if the function is async (a similar quick and dirty check like generators) and if it is, call await fn() instead. This of course requires the containing function to be async, which in turn screws up all the existing throw() assertion tests.

When it's called, the parser steps into the function and immediately returns the resulting string. textContent = `There was a problem: ${error}`; Another popular method for dealing with asynchronous code is called promises  In actuality, async void methods when factored with its weird exception handling behavior (discussed next) is really a fire and hope to forget feature. 3. async void can be disastrous If a developer unwittingly adds an async keyword to a void method, making the method an async void method. That developer has just added a time bomb to their application.

async function asyncFunc () { throw new Error ( 'Problem!' ); } asyncFunc Handling a single asynchronous result: Handling multiple asynchronous results sequentially: Another option is an Immediately Invoked Async Arrow Function:. There’s a special syntax to work with promises in a more comfortable fashion, called “async/await”. It’s surprisingly easy to understand and use. Let’s start with the async keyword. It can be placed before a function, like this: The word “async” before a function means one simple thing: a function always returns a promise.

But first of all, since Promises are the foundation of Async functions, to be There are few issues that I have been through into while playing with this, We need to call .catch on the Promise and duplicate our error handling code, which (even the asynchronous ones) will execute one after the another. TypeScript Version: 1.8.10 Tested with node v6.1.0 I have an async function that returns a Promise. If I call resolve() everything works file. If I call reject(), await will not throw any exception and program will just hang.

Comments
  • without await , it output Promise { undefined } with await , it output undefined
  • @27mdmo7sn So that would imply, rates.data.data is undefined, did you mean to do rates.data ?
  • @keith maybe that or its just because he commented before my edit, and still refers to his code which doesnt return anything from A
  • Yes @JonasWilms , You're right your answer worked with me , it is more simple/easy without using promises
  • I mean it's simple without declaring a new Promise and return reject or resolve , that's was a bit not easy