簡體   English   中英

JavaScript 異步等待在 forEach 循環中不起作用

[英]JavaScript async await doesn't work inside forEach loop

我對要收集到事務中的數據庫的查詢很少。

let t = await db.sequelize.transaction()
  try {
    let adr = await addressRepo.add(address, t)
    let user = await userRepo.add(email, password, name, surname, phone, NIP, REGON, id_number, adr.id, t)
    await userRoleRepo.add(user.id, user_role, t)
    if (languages != null) {
      languages.forEach(async function (language) {
        await userLanguageRepo.add(user.id, language.id, language.main, t)
      })
    }
    await t.commit()
    res.status(201).json(user)
  } catch (error) {
    await t.rollback()
}

根據上面的代碼,事務被創建並且除了forEach循環之外的所有查詢都包括在內。 結果我得到:

Executing (fb270893-9146-43b7-a35e-8960ea386513): START TRANSACTION;
Executing (fb270893-9146-43b7-a35e-8960ea386513): INSERT INTO `address` (`id`,`country`) VALUES (DEFAULT,'country');
Executing (fb270893-9146-43b7-a35e-8960ea386513): INSERT INTO `user` (`id`,`email`,`password`,`name`,`surname`,`active`,`address_id`,`created_at`,`updated_at`) VALUES (DEFAULT,'a15','$2a$10$7uImQNl0T12CZLUB0Asxwu8yCGUa/eZnbr8TATX8V/tnnO8erdYzy','John','Dee','0',15,'2017-08-28 07:44:03','2017-08-28 07:44:03');
Executing (fb270893-9146-43b7-a35e-8960ea386513): INSERT INTO `user_role` (`user_id`,`role_id`) VALUES (7,1);
Executing (fb270893-9146-43b7-a35e-8960ea386513): COMMIT;
(node:5873) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: commit has been called on this transaction(fb270893-9146-43b7-a35e-8960ea386513), you can no longer use it. (The rejected query is attached as the 'sql' property of this error)
(node:5873) [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:5873) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): Error: commit has been called on this transaction(fb270893-9146-43b7-a35e-8960ea386513), you can no longer use it. (The rejected query is attached as the 'sql' property of this error)

我查看了異步提交是在 forEach 循環之前執行的。 如何在提交之前執行 forEach 循環?

而不是forEach應該for of循環。

我在這篇文章中找到了答案。

暫無
暫無

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

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