Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

325
Vistas
How to stop async calls within a js map function (Node Js)

I have this updateGameScore asynchronous service function, which is used to add new record if there's no record already in the GameScore collection with the perticular user ID, or update relevant record if exists:

const updateGameScore = async (userId, gameId, score, date, res) => {

    const gameScore = await GameScore.findOne({ userId });

    //If no record found with given userId, a new record will be created
    if (!gameScore) {
        let newGameScore = new GameScore({
            userId,
            gameScores: { gameId, highScore: score },
            totalScore: score,
            date,
        });

        newGameScore = await newGameScore.save();
    }
    //If there is already a record of the given userID
    else {
        //The totalscore field of that user will be updated by adding the new score to the current total score
        const totalScore = gameScore.totalScore + score;
        await GameScore.findByIdAndUpdate(
            { _id: gameScore._id },
            { totalScore, date }
        );
    }

And then I call this function within a map function to make 50,000 calls from a db collection that already exist.

    allPlayers = await Player.find();
    await allPlayers.map((player) => {
        const userId = player.userId;
        const gameId = player.gameId;
        const score = player.score;
        const date = player.date;

        updateGameScore(userId, gameId, score, date, res);
    });

However my code, the updateGameScore function works properly(if I call it one by one). but when I call 50,000 records at once, all records call this function parallelly, and makes 50,000 new records on my GameScore collection, which I do not need to happen. I just need to create new record if a record with the given userId doesn't exist but update the record if a record with given ID exist. This would work properly if my map function call the updateGameScore function sequntially, but unfortunately it does not. Please help me with this as I have very poor knowledge in asynchronous js.

about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda