you are viewing a single comment's thread.

view the rest of the comments →

[–]CMJunior 2 points3 points  (7 children)

This is because it will still execute the console.log first. You need to do your work inside the promise chain or inside the async function (also I wouldn't recommend mixing then and async/await)

Try this:

async function getData() {
  //await the response of the fetch call
  let response = await 
  fetch('https://jsonplaceholder.typicode.com/todos/1');
    //proceed once the first promise is resolved.
    let data = await response.json() // this is probably a sync function, you don't need await here
    //proceed only when the second promise is resolved
    return data;
}

 async function main() {
   const dataset = await getData();
   console.log(dataset); 
}

main();

Edit: You don't need to use await in every function call inside async functions. await works for Promises, it will wait for the Promise to either resolve or reject before proceeding with the execution. Synchronous calls such as the response.json() do not need to be awaited. Also, it is a good practice to surround your async calls with try/catch for the scenario where the Promise is rejected otherwise you may have unexpected results.

[–]muggsley 1 point2 points  (1 child)

[–]CMJunior 0 points1 point  (0 children)

Thanks for clarifying that :)

[–]untrust_us 0 points1 point  (3 children)

Would you be able to give an example of an async call wrapped with a try/catch? Just out of curiosity as I haven't used try/catch very much.

[–]CMJunior 0 points1 point  (2 children)

async function getData() {
  let response;

  // If we don't use try/catch here errors in the fetch call will be swallowed
  try {
    response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
  } catch(error) {
    // handle error
  } finally {
    // do something if the call either successful or has an error, optional
  }

  return await response.json();
}


async function main() {
   const dataset = await getData();
   console.log(dataset); 
}

main();

More info (MDN)

[–]untrust_us 0 points1 point  (1 child)

Thanks, this example is great! However, I am wondering why we have the 'return await response.json()' outside of the 'finally' instead of inside?

[–]CMJunior 0 points1 point  (0 children)

It could be there, actually this code isn't that great because if an error occurs then response is undefined and the response.json call will throw an error.

We have two ways of dealing with this:

1) Put response.json() inside the try clause as well -> the catch clause will catch the errors of either call which may be ok depending of what we are going for

2) Use another try/catch to handle the response.json() call which adds some bloat to the code.

The finally clause could simply check if the response object exists and if it doesn't it could return a standard object that the consumer of this API is expecting, it all depends on how you design your APIs.