Need Little clarification on Promise/async/await pls

Hi, after learning a bit about JavaScript Promises and async/await i have a a few questions.

  • While a function is paused at a line with the await keyword and it taking too long time to reject or fulfill. How to i move on without resorting to using the await keyword on a line that uses the returned promise?

  • Why did they use await on Promise.all ( let values = await Promise.all([coffee, tea, description]);)?

what i think:

  1. The first line of code below has called itfunction. And with await attached to the fetch ApI, it should pause the code. make its request… and store the returned promise in the cofee variable. Then after, let tea can resume…
  let coffee = fetchAndDecode('coffee.jpg', 'blob');
  let tea = fetchAndDecode('tea.jpg', 'blob');
  let description = fetchAndDecode('description.txt', 'text');

A direct link to the section on MDN

The code didn’t work without await on Promise.all, though.

It now seems like let coffee = fetchAndCode('coffee.jpg', 'blob') just called the function and moved on without allowing the function to finish first, and so on

You really can’t skip await unless the function you’re awaiting on throws an error.
That’s why await code should be wrapped inside try...catch. In case of error, execution of the code in try block stops and the code in catch is run.

Promise.all takes an array of promises and runs them all in parallel and just as with any promise, you are not getting results immediately, that’s why you have to await. Without await the value of values will be just a pending promise (I guess :thinking:) and it’s not what code after Promise.all expects.

let coffee = fetchAndDecode('coffee.jpg', 'blob');
let tea = fetchAndDecode('tea.jpg', 'blob');
let description = fetchAndDecode('description.txt', 'text');

This just creates promises one after another, without waiting. You could add await before each fetchAndDecode(), but that would force all those promises to run one after another (that’s why you would use Promise.all - to run them simultaneously).

1 Like

Thanks for this! That’s all cleared. But anyway around the first question?

If you mean moving past await, I think I already answered: you can’t. Unless the function you’re awaiting throws an error that you can catch by wrapping your code in try...catch

Thanks! I got an idea with setimeout and try…catch