Search code examples
reactjsasynchronouspromiseuse-effect

Why doesn't the parser wait for Promise.resolve?


I am using React and I do not understand why in the useEffect when running a map function the second part of the code runs before the first part (which is a promise resolve). Shouldn't the parser wait for the promise to resolve and then run the second part of the code?

  useEffect(() => {

    const pools = mainnet.Exchanges.Pancakeswap.LpTokens.map((lpPool) => {
        // part 1
        const [tokenZeroSymbol, tokenOneSymbol] = lpPool.name.replace(' LP', '').split('-');
        const prices = fetchTokenPrice(tokenZeroSymbol.toLowerCase(), tokenOneSymbol.toLowerCase());
        Promise.resolve(prices).then((values) => {
          const [priceTokenZero, priceTokenOne] = values;
          filteredFarmPools.find((pool) => {
            if (lpPool.name.replace(' LP', '') === pool.name) {
              pool.priceTokenZero = values[0].usd;
              pool.priceTokenOne = values[1].usd;
            }
            console.log('inside the fethcprice promise');
          });
        });


        // part 2
        filteredFarmPools.find((pool) => {
          if (lpPool.name.replace(' LP', '') === pool.name) {
            const tvl0 = (pool.reserveTokenZero / 10 ** 18) * pool.priceTokenZero;
            const tvl1 = (pool.reserveTokenOne / 10 ** 18) * pool.priceTokenOne;
            pool.tvl = tvl0 + tvl1;
          }
          console.log('inside the tvl calc');
        });
    });

Solution

  • No.

    Promises give you an object that you can pass around and call then on.

    They do not turn asynchronous code into blocking code.


    The second part of the code isn't inside the then callback so it runs while the asynchronous code (that will trigger the first promise to resolve) is running in the background.


    That said, see the await keyword for asyntax that can give the illusion that a promise is blocking.