簡體   English   中英

在循環內使用帶有異步/等待的循環 + nodejs

[英]Using loop with async/await inside loop + nodejs

您好,在我的 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循環,但沒有成功,並且從上面的 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)

任何幫助將不勝感激

我可以看到兩個問題:

首先,地圖調用中的等待並不像您想象的那樣工作。 它可以在 for-of 循​​環中正常工作,但不能在地圖、foreach 等中正常工作。

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

其次,在您調用 let Users = Users.findOne 的地方,編譯器認為分配左側的用戶與右側的用戶相同,因此它抱怨在調用 Users.findOne 時,用戶不是t 初始化。

要在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); })();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM