与循环一起使用循环/ nodejs内的await / await循环

问题描述 投票:0回答:1

您好在我的nodejs api中,我需要在循环内获取数据,然后再次需要执行循环并将数据保存在另一个表中,我应该如何实现?这是我尝试但未成功执行的一些代码段

async myAPIname(){
    let _this = this;
    try {

        const bets = await Bet.find({gameId:ObjectId(request.matchId)}).lean()

        bets.map(async (bet) => {
            let Users  = await Users.findOne({_id:ObjectId(element.userId)}).lean();
            Users.parentTree.map(async (user) => {
                console.log(user);
                // also over here based on the some calculation need to save the data in another table
            })
        })

    } catch (error) {
        _this.res.send({ status: 0, message: error });
    }

}

也同样在上述片段中尝试了foreach循环,但未成功和上面的小刺这样的错误:

(node:30886) UnhandledPromiseRejectionWarning: ReferenceError: Cannot access 'Users' before initialization
at /var/www/html/api/app/controllers/SomeController.js:228:30
at Array.map (<anonymous>)
at SomeController.myAPIname (/var/www/html/api/app/controllers/SomeController.js:227:18)
at processTicksAndRejections (internal/process/task_queues.js:97:5)

(node:30886) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)

(node:30886) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
(node:30886) UnhandledPromiseRejectionWarning: TypeError: Assignment to constant variable.
    at /var/www/html/api/app/controllers/SomeController.js:220:27
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:30886) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)

任何帮助将不胜感激

javascript node.js typescript loops async-await
1个回答
0
投票

我可以看到两个问题:

首先,在地图调用中等待并不像您想的那样工作。它可以在for-of循环中正常运行,但不能在map,foreach等环境中运行。

https://zellwk.com/blog/async-await-in-loops/在任何地方都有很好的解释。

第二个调用let Users = Users.findOne的地方,编译器认为分配左侧的Users与右侧的Users相同,因此它抱怨说,在调用Users.findOne时,Users尚未初始化。

© www.soinside.com 2019 - 2024. All rights reserved.