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);
})
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:
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
})
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).
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.