在使用带有异步等待的Sequelize事务时,可以返回承诺吗?

时间:2018-12-28 16:21:27

标签: transactions async-await sequelize.js

假设我有一个名为Item的表,其中的字段名为“ name”。名称字段上有一个唯一的键约束。为什么在等待调用时这两个函数的行为会有所不同?唯一的区别是,一个在销毁物品之前等待,而另一个则返回销毁的保证。这些用途不应该完全相同吗?

const createAndDestroyWorksFine = async (name) => {
    await Item.create({ name })
    const item = await Item.findOne({ where: { name } });
    await item.destroy();
}

const createAndDestroyCausesError = async (name) => {
    await Item.create({ name })
    const item = await Item.findOne({ where: { name } });
    return item.destroy();
}

async function test() {
    // this works
    await transaction(createAndDestroyWorksFine('item'));
    await transaction(createAndDestroyWorksFine('item'));

    // this fails often, with a duplicate key error
    await transaction(createAndDestroyCausesError('item'));
    await transaction(createAndDestroyCausesError('item'));
}

test()

0 个答案:

没有答案
相关问题