【问题标题】:Using loop with async/await inside loop + nodejs在循环+ nodejs中使用带有异步/等待的循环
【发布时间】:2020-03-12 17:59:46
【问题描述】:

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

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循环,但没有成功 和来自spinet上面的错误是这样的:

(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】:

    我可以看到两个问题:

    首先,map 调用中的 await 并不像您想象的那样工作。它可以在 for-of 循​​环中正常工作,但不能在 map、foreach 等中工作。

    https://zellwk.com/blog/async-await-in-loops/ 有一个很好的解释。

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

    【讨论】:

      【解决方案2】:

      要对Array.prototype.map() 使用异步处理,您必须用Promise.all() 包装它并等待它完成。

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

      const sleep = async (time = 3000) => new Promise(resolve => setTimeout(resolve, time));
      
      (async () => {
        const array = [1,3,4,2];
        console.log('start', array);
        const mapped =await Promise.all(array.map(async e => {
          await sleep(e * 1000);
          console.log(e);
          return `done for ${e}`;
        }));
        console.log('end', mapped);
      })();

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-04-15
        • 1970-01-01
        • 2021-12-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多