Vish
Vish

Reputation: 175

How to await on async function and collect the response

Until now, I thought await makes my program synchronous. However, I see that await only waits for async function to be resolved with a promise then the whole programs continues to run. So, what is the right way to wait & collect the response from async function?

Original code:

let result={
  name:'',
  country:''
};
const data = await query.getCachedData(did); 
result.name = data.name; // undefined
result.country = data.country;//undefined
console.log(result);

I don't know why but awaiting on the async function result works:

let result={
  name:'',
  country:''
};
const data = await query.getCachedData(did); 
result.name = await data.name; //'Jon'
result.country = await data.country;// 'US'
console.log(result);

But I am not sure if this is the solution.

Since getCachedData returns the promise, I thought this may be the right way but the then()/catch() didn't execute.

query.getCachedData(did).then((tfnData) => {
  result.name = data.name; 
  result.country = data.country;
  console.log(result);
}).catch((dbError) => {
  console.log(dbError);
});

Can anyone correct me to get the result the right way?

Upvotes: 2

Views: 2896

Answers (4)

Janneck Lange
Janneck Lange

Reputation: 932

A Promise is the return from a async function. The result is maybe not finish yet. That is why you can await a method (like you did it). This will set the return from the function when the calculation is complied.

Or you can make use of 'then':

const data1 = await query.getCachedData(did);
//data1 has a value at this point of code

const data2;
query.getChachedData(did).then((result)=>{data2 = result});
//data2 can have a value or will get one later (this is async) at this point of code

With Promise all you can let multiple methods run asynchronous and wait for all at once. https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

const callStack = [];

const data1;
const data2;
callStack.push(query.getChachedData(did).then((result)=>{data1 = result}));
callStack.push(query.getChachedData(did).then((result)=>{data2 = result}));
//run both query Methods at asynchronous 
await Promise.all(callStack);
//data1 and data2 hava a value at this point of code

Upvotes: 1

robe007
robe007

Reputation: 3927

Until now, I thought await makes my program synchronous

Async/await makes the code to looks like synchronous, but behind is just syntactic sugar for promises in Javascript. Really? Yes

Is just return thePromise().then(result => result)

I see that await only waits for async function to be resolved with a promise then the whole programs continues to run

When you work with promises, they not make Node.js code run synchronous, in the other hand, promises allow you to write flows that appear synchronous.

So, what is the right way to wait & collect the response from async function?

According to your example, the code will be something like this:

const queryResult = did => query.getCachedData(did).then(tfnData => tfnData);

// Without async/await    
queryResult(did)
  .then(data => {
    const { name, country } = data;
    const result = { name, country };
    console.log(`${result.name}, ${result.country}`); // Jon, US
  })
  .catch(error => console.log(`Error produced: ${error}`));

// With async/await
(async () => {
  try {
    // ... Some other code ....
    // ... Some other code ....
    // ... Some other code ....

    const data = await queryResult(did);
    const { name, country } = data;
    const result = { name, country };
    console.log(`${result.name}, ${result.country}`); // Jon, US
  } catch (error) {
    console.log(`Error inside try-catch: ${error}`);
  }
})();

Upvotes: 1

ehab
ehab

Reputation: 8024

await does not make your asynchronous code synchronous - and there should not be any reasonable reason to do so ... behind the scenes it returns a promise and chain it with then instead of you having to chain it with then yourself.

What you did with the then keyword, is what the await did for you.

You can use whatever suits you, but async/await makes your code easier to read.

if this works

result.name = await data.name; 

this means that the name is an async getter function that you have to await for it to get the result. You can do it also like this data.name.then(name => doWhateverYouWantWithName(name)) or using the await keyword like you already did - and that should be better even.

Upvotes: 0

Dan Buda
Dan Buda

Reputation: 348

You are correct that await waits for an async function to return a promise. For your code example, I would suggest the following:

let result={
    name:'',
    country:''
};

async function getData() {
    const data = await query.getCachedData(did);
    result.name = data.name; // 'Jon'
    result.country = data.country; // 'US'
    console.log(result);
}

await can only be used inside an async function. It will pause the function until a promise is received from query.getCachedData(), save that response into const data which can then be used to set the name and country of the result object. You can also look at the MDN docs for both async and await.

Upvotes: 0

Related Questions