Is await + a try block a "resolve" equivalent?

I know the literal meaning of await is “stop execution until async operation completes.” Is that basically the same as a Promise.resolve() operation? I am learning async/await now and i see these 2 as equal:

const getGoogle = async () => {
  try {
    const response = await fetch('google.com'); // response is captured only if stream resolves to Response object.
    const data = await response.json(); // data is captured to variabled after being mutated into json object.
    return data;
  }
}

const getYahoo = new Promise(resolve => {
  fetch('yahoo.com')
    .then(response => response.json())
    .then(data => data);
})

await is is the very short answer.

It resolves whatever comes after it, like running Promise.resolve

try/catch is equivalent of

somePromise
  .then(resp => /* dostuff */)
  .catch(err => /* dostuff with error */)

Hi @SeanDez, if you rephrase “stop execution until async operation completes” to “stop execution until promise has resolved” it would add some clarity I believe. Then taking it further, what’s awaiting for Promise to be resolved in the case with Promises? It’s .then() method, so await === .then()

Few more remarks:

  1. If you want your getYahoo example to work you need to resolve Promise like this:
const getYahoo = new Promise(resolve => {
  fetch('yahoo.com')
    .then(response => response.json())
    .then(data => resolve(data)); // <-- HERE
})
  1. try/catch has nothing to do with async/await and in practice you can write code without try/catch, you only need it when you want to catch error if something goes wrong with async operation (aka Promise).
  2. I’m pretty sure you know it but still everyone shall not forget one BIG difference between Promises and async/await - you can only use await inside async function. On other hand, .then() can be used wherever you want in your code.

Cheers!

1 Like

Thank you iked, completely forgot to use resolve! I would have used it on the 1st .then() like this:

    .then(response => resolve(response.json())

I take it this is not right? But I thought the resolved value is what goes into the argument for the next ,then() handler?

This won’t work as .json() return Promise. In your case you need to resolve in the second .then() or do something like this:

.then(async (res) => {
   const response = await res.json();
  resolve(response);
})
1 Like