具有for循环的多个异步等待

时间:2020-11-08 03:21:04

标签: javascript async-await watermelondb

我想用async / await运行多个功能,包括for循环。循环也需要相互运行完成。目前,我正在使用此功能,似乎无法正常工作。

对于for循环查询,我需要在第一个查询中创建的ID才能执行。

const createStudent = async (studentObj) => {
    try {
        await database.action(async () => {
            const newStudent = await studentCollection.create(student => {
                student.name = studentObj.name
                student.age = studentObj.age
            })

            for (let contactObj of studentObj.contacts) {
                try {
                    await contactCollections.create(contact => {
                        contact.student_id = newStudent.id
                        contact.type = contactObj.type
                        contact.contact = contactObj.contact
                    })
                } catch (error) {
                    console.log(error);
                }
            }
        })
    } catch (error) {
        console.log(error);
    }
}

当前我遇到错误

[WatermelonDB] The action you're trying to perform (unnamed) can't be performed yet, because there are 2 actions in the queue. 
Current action: unnamed. Ignore this message if everything is working fine. 
But if your actions are not running, it's because the current action is stuck. 
Remember that if you're calling an action from an action, you must use subAction(). See docs for more details.

1 个答案:

答案 0 :(得分:1)

是的,您是对的!它不能与多个数据库一起创建记录请求一起正常工作。

每当您在一项操作中进行多个更改(创建,删除或更新记录)时,都应进行批量处理。

请参阅:https://nozbe.github.io/WatermelonDB/Actions.html

您可以这样做:

const batchActions = [];

for (let contactObj of studentObj.contacts) {
  batchActions.push(
    contactCollections.prepareCreate(contact => {
      contact.student_id = newStudent.id
      contact.type = contactObj.type
      contact.contact = contactObj.contact
    })
  )
}

database.batch(batchActions)

希望这可以解决您的问题