O
O
olezhenka2019-08-16 17:07:21
JavaScript
olezhenka, 2019-08-16 17:07:21

How to make all requests wait for one promise?

Many users perform an action where I either need to pick up an object with a variable, and if it is not there, load it from the database and write it to this variable.
The problem is when many users quickly perform an action, I have duplicate requests to the database and the objects themselves too. How to make subsequent requests, after the first download request, wait for the first one, and not start loading themselves?

// внутри async function
chat.quiz = global_quizzes[quiz_id];
if(!chat.quiz) {
    // проблема в дубли
    chat.quiz = await Chat_Quizzes.findById(quiz_id).exec();
    global_quizzes[quiz_id] = chat.quiz;
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Inviz Custos, 2019-08-16
@olezhenka

You can use queue
Example:

'use strict';

const { Queue } = require('plain-queue');
const queue = new Queue;

// внутри async function
    chat.quiz = global_quizzes[quiz_id];
    
    if(!chat.quiz) {
        chat.quiz = await queue.addTask(function () {
            return global_quizzes[quiz_id] || Chat_Quizzes.findById(quiz_id).exec();
        });

        global_quizzes[quiz_id] = chat.quiz;
    }

V
Vitaly, 2019-08-16
@vshvydky

ORM + CASH...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question