简体   繁体   中英

NodeJS concurrent requests response is mixed

When concurrent requests are made the response data is mixed.

The route controller injects the dependencies to the use-case functions.

Route controller

const fromAdaptReq = require('../../utils/adapt-req');
...other imports

router.get('/v1/getList', async (req, res, next) => {
    try {
        const request = {
                      locals: res.locals,
                      lang: res.locals.lang
                     };

        const userCase = new fromUsersCase
            .user
            .user
            .getList({
                createError: customError.CustomError,
                translate,
                request: request,
                db: fromDB.database,
            });
        const result = await userCase.execute();
        return res.status(200).json({
            msg: result.msg,
            data: result.data,
            error: false
        });
    } catch (error) {
        console.log(error)
        next(error);
    }
}

Search listing function is used to call the query function

search listing function

exports.getList = function ({ createError, translate, request, db }) {
    return Object.freeze({
        execute: async () => {
            try {
                const userId = parseInt(request.locals.userId);

                const searchList= await fromServices
                                        .getPhonebook(request.lang, createError, translate, { userId, db });

                return {
                    msg: 'List',
                    data: { list: searchList}
                }
            } catch (error) {
                if (error instanceof createError) {
                    throw error;
                }
                console.log(error);
                throw new Error(error.message);
            }
        }
    })
}

I found that I was using the global variable to store the user-id inside the fromService function which was performing the query based on user id to generate the list.

Changing blocked scope fixed the error Thank you

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM