Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

170
Views
La función ForEach no realiza acciones en cada objeto, solo una vez

Estoy creando una aplicación de construcción de mazos para un juego de cartas, también tengo una configuración de base de datos que uso para vender estas cartas con las que juego, este creador de mazos me permite tomar del stock del stock vendible (es decir, si tengo 1 de x, y lo {deck} a un mazo, establece el countInStock de existencias de ese elemento en la base de datos en 1 menos de lo que era). que estaba en [deck.cards] que es una matriz de objetos {Card} , estoy tratando de simplemente recorrer cada objeto en esa matriz, encontrar esa tarjeta, encontrar el producto en la base de datos, establecer el producto en +1 (ya que cada tarjeta, puede ser la misma tarjeta, pero será un objeto diferente), por lo tanto, simplemente necesito aumentar el countInStock en stock en 1, cuando llegue a este punto final, volverá a colocarse en el objeto de stock 1, pero aparentemente ignorará el otros objetos en el ciclo forEach y no agregar más al conteo en stock, no estoy seguro de por qué funcionará una vez, pero no funcionará cada uno h iteración.

código:

 /** * @description This function removes a deck from the database, and re-seeds whatever cards where in that deck * back into the sellable stock * * @route DELETE /api/deck/:deckId * @param deckId ObjectID of the deck * @comment hitting this route will change the countInStock value of the {product} * in the database by whatever cards where in the [deck.cards] * */ module.exports = asyncHandler(async (req, res) => { try { // find the deck const deck = await Deck.findById(req.params.id); // check if it exists if (!deck) { return res .status(404) .json({ message: `Deck: ${req.params.id} cannot be found` }); } // we need to run a foreach command over every object in [deck.cards] await deck.cards.forEach(async (c) => { console.log(c); // find the card const card = await Card.findById(c._id); // We then need to find the sellable { Product } and add back to it, so it can be sold/traded const product = await Product.findById(card.productId); // increase the amount of inStock sellable items, by 1. await product.set({ countInStock: product.countInStock + 1 }); await product.save(); // if we get here we want to remove the card object from the database, its just a placeholder. await card.remove(); }); // remove the deck await deck.remove(); res.status(200).json({ success: true }); } catch (error) { console.error(error); res.status(500).json({ message: `Server Error: ${error.message}` }); } });
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Intentaré describir la explicación dada por @jfriend00 tanto como sea posible.

Muchos, incluyéndome a mí, pensaron que forEach es una versión simplificada del ciclo for , pero la verdad es que IT IS NOT cuando se trata de la async await . Por ejemplo, tomemos este código:

 const loopThis = [1, 2, 3, 4]; function timeOut2000() { return new Promise(resolve => setTimeout(resolve, 1000)); } async function loopThrough() { await loopThis.forEach(async x => { await timeOut2000(); console.log(x) }); } loopThrough()

Al ejecutar lo anterior, podemos ver que no espera el timeOut2000 en cada ciclo, porque no espera que se resuelva cada promesa.

Para lograr la async await para cada ciclo, podemos usar for loop o for .. in .. como se muestra a continuación:

 const loopThis = [1, 2, 3, 4]; function timeOut2000() { return new Promise(resolve => setTimeout(resolve, 1000)); } async function loopThrough() { for (const x of loopThis) { await timeOut2000(); console.log(x) }; } loopThrough()

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!