dartmouth-cs52 / dartmouth-cs52.github.io

CS52 Course Website
https://cs52.me
9 stars 40 forks source link

add async-await back into the frontend babel #268

Open timofei7 opened 4 years ago

timofei7 commented 4 years ago

1) async fetch some A 2) if A fulfills some condition, async fetch some B 3) if B fulfills some condition, async fetch some C 4) return { x: A.a, y: C.c } (some random attributes from both) I struggle to use promises with this since I have the following mental model:

fetch(A)
.then((A) => {
   if (check(A) return fetch(B);
})
.then((B) => {
   if (check(b) return fetch(C);
})
.then((C) => {
  return { x: A.a y: C.c };
  // but A is out of scope here!!
})
.catch(whatever);

This is trivial to do with async/await since scope remains the same throughout. Perhaps there’s a workaround for this that I don’t know about, but this feels like a headache. (edited)

yeah, if you need previous values further in the chain it gets a bit gross. that is a great case for using await. before await i might have hacked it so there is an intermediary function:

Fetch(A)
.then((resultA) => {
   if (check(resultA) return fetch(B).then( resultB => [resultA, resultB])
})
.then( [resultA, resultB] => {
   if (check(resultB) return fetch(C).then( resultC => [resultA, resultB, resultC])
})
.then([resultA, resultB, resultC] => {
  etc

other ways to solve: make an exercise with something like this: https://stackoverflow.com/questions/28250680/how-do-i-access-previous-promise-results-in-a-then-chain