1

I'm trying to fetch the products within an order using a Promises

function BuscaPedidos(pedidos) {
  return new Promise((resolve, reject) => {
    let results = [];
    let erro = false;
    for (const pedido of pedidos) {
      //console.log(pedido)

      BuscaProdutosPedido(pedido.id)
        .then(listaProdutos => {
          //console.log(listaProdutos)
          let p;
          p = { ...pedido,
            'produtos': listaProdutos
          }
          console.log(p)
          results.push(p);
          console.log(results)
        })
        .catch(error => {
          erro = true
        })

    }
    console.log(results)
    if (!erro && results.id) {
      console.log(results)
      resolve(results);
    } else {
      reject("Results  vazio")
    }
  })
}

In the first console.log it returns the data inside the results variable. The second console.log returns empty, can someone help me?

Barmar
  • 741,623
  • 53
  • 500
  • 612
felipe11
  • 11
  • 1
  • The dupe target is accurate, but your code is somewhat more complex than any represented there. The issue is that you are effectively not waiting for `BuscaProdutosPedido` to finish. You'll likely want to chain some more `.then` calls, and `return` the promise from `BuscaProdutosPedido`, but you'll need to refactor away the `for` loop. Best of luck. – CollinD Nov 18 '22 at 17:39
  • @CollinD The problem is that my results variable doesn't have the values ​​outside the promise's then, and I don't understand why – felipe11 Nov 18 '22 at 17:54

0 Answers0