2

Codesandbox: https://codesandbox.io/s/aged-meadow-s4hzi?file=/src/App.js:100-972

I am using Promise.resolve().then in App.js, but the result in Console is different from what I am expecting.

My expectation:

first then 
Change res to 1 
second then 
1

But the actual result

first then 
second then 
0
Change res to 1 

App.js

useEffect(() => {
    var res = 0;
    let myPromises = [myPromise, myPromise, myPromise];
    let mySecondPromises = [myPromise, myPromise];

    Promise.resolve()
      .then(() => {
        console.log("first then");
        Promise.all(myPromises)
          .then((res) => {
            return mySecondPromises;
          })
          .then((arr) => {
            return Promise.all(arr)
              .then((res) => {
                if (true) {
                  console.log("Change res to 1");
                  res = 1;
                }
              })
              .catch((err) => {...});
          })
          .catch((err) => {...});
        return res;
      })
      .then((res) => {
        console.log("second then");
        console.log(res);
      });
  }, []);
CCCC
  • 5,665
  • 4
  • 41
  • 88
  • 1
    How is react relevant here? You would get the same result in any other context!? So simply asking about javascript and promises might yield better/faster answers. – Yoshi Jul 29 '21 at 07:42
  • 1
    `return res;` is the cause because `second then` comes before `Change res to 1`. Returns before resolve `Promise.all(myPromises)`. – Giovanni Esposito Jul 29 '21 at 07:46
  • @Giovanni Esposito is there any method to make sure the `second then` run after `first then` finish? – CCCC Jul 29 '21 at 07:47
  • @CCCC I've made a couple of changes to your codesandbox so that it behaves the way that you wanted: https://codesandbox.io/s/fancy-lake-i0gcc?file=/src/App.js – Josep Jul 29 '21 at 07:50
  • 2
    Having nested `.then()` calls is a code smell. You *should not need them*. Promises are designed to avoid this behaviour. See [Aren't promises just callbacks?](https://stackoverflow.com/q/22539815). Usually it's a sign that promises are mis-used which is then usually the reason whatever "doesn't work" in the question to not work. – VLAZ Jul 29 '21 at 07:54

0 Answers0