Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/37.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用带有异步/等待内部循环的循环+;nodejs_Javascript_Node.js_Typescript_Loops_Async Await - Fatal编程技术网

Javascript 使用带有异步/等待内部循环的循环+;nodejs

Javascript 使用带有异步/等待内部循环的循环+;nodejs,javascript,node.js,typescript,loops,async-await,Javascript,Node.js,Typescript,Loops,Async Await,您好,在我的nodejsapi中,我需要在循环中获取数据,然后再次需要执行循环并将数据保存在另一个表中,我应该如何实现这一点? 下面是一些我尝试过但同样失败的片段 async myAPIname(){ let _this = this; try { const bets = await Bet.find({gameId:ObjectId(request.matchId)}).lean() bets.map(async (bet) => {

您好,在我的nodejsapi中,我需要在循环中获取数据,然后再次需要执行循环并将数据保存在另一个表中,我应该如何实现这一点? 下面是一些我尝试过但同样失败的片段

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)
(节点:30886)未处理的PromisejectionWarning:ReferenceError:在初始化之前无法访问“用户”
在/var/www/html/api/app/controllers/SomeController.js:228:30
在Array.map()处
在SomeController.myAPIname(/var/www/html/api/app/controllers/SomeController.js:227:18)
在处理和拒绝时(内部/process/task_queues.js:97:5)
(节点:30886)未处理的PromisejectionWarning:未处理的承诺拒绝。此错误源于在没有catch块的异步函数中抛出,或者拒绝未使用.catch()处理的承诺。要在未处理的承诺拒绝时终止节点进程,请使用CLI标志“---unhandled rejections=strict”(请参阅https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (拒绝id:1)
(节点:30886)[DEP0018]弃用警告:未处理的承诺拒绝已弃用。将来,未处理的承诺拒绝将使用非零退出代码终止Node.js进程。
(节点:30886)未处理的PromisejectionWarning:TypeError:分配给常量变量。
在/var/www/html/api/app/controllers/SomeController.js:220:27
在处理和拒绝时(内部/process/task_queues.js:97:5)
(节点:30886)未处理的PromisejectionWarning:未处理的承诺拒绝。此错误源于在没有catch块的异步函数中抛出,或者拒绝未使用.catch()处理的承诺。要在未处理的承诺拒绝时终止节点进程,请使用CLI标志“---unhandled rejections=strict”(请参阅https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (拒绝id:2)

非常感谢您的帮助

我发现两个问题:

首先,地图调用中的等待不像你想象的那样工作。它可以在for of循环中正常工作,但在map、foreach等中则不行

在任何地方都有很好的解释


其次,当您调用let Users=Users.findOne时,编译器认为赋值左侧的用户与右侧的用户相同,因此它抱怨在调用Users.findOne时,用户没有初始化。

使用异步处理
Array.prototype.map()
你必须用
Promise.all()来包装它,然后等待它实现

!!但是请注意,迭代是以异步方式执行的,而不是等待上一次迭代的结束

const sleep=async(time=3000)=>newpromise(resolve=>setTimeout(resolve,time));
(异步()=>{
常量数组=[1,3,4,2];
log('start',数组);
常量映射=等待承诺.all(array.map)(异步e=>{
等待睡眠(e*1000);
控制台日志(e);
返回`done for${e}`;
}));
console.log('end',已映射);
})();