await在forEach循环中不起作用

await在forEach循环中不起作用

本文介绍了JavaScript async await在forEach循环中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对数据库的查询很少,我想收集到一个事务中。

I have few queries to a database which I want to gather into a transaction.

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循环中的查询之外,还包括所有查询。结果我得到:

According to above code, the transaction is created and all queries are included except of those in forEach loop. As a result I get:

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循环?

I looked at async commit is execute before forEach loop. How can I execute forEach loop before commit?

推荐答案

而不是 forEach 一个人应该使用来获取循环。

Instead of forEach one should use for of loop.

我在。

这篇关于JavaScript async await在forEach循环中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 01:38