gpt4 book ai didi

JavaScript 异步/等待 : await is a reserved word

转载 作者:行者123 更新时间:2023-12-03 03:08:45 25 4
gpt4 key购买 nike

这是一个检查 mongoose 是否有重复记录的函数。在这种情况下nameemail是唯一字段,因此如果数据库中存在具有相同名称或电子邮件的记录,则无法插入新记录:

const checkIfDatabaseHasUsersWithSameNameAndEmail = async () => {

uniques = ['name', 'email'];
uniques.map((field) => {
let query = {};
query[field] = data[field];
query.deleted = false;
let result = await model.findOne(query); <== ERROR: await is a reserved word

if (result) {
errors.push({
field: field,
message: 'A record already exists in database for ' + field + '=' + data[field]
});
}
});

if (errors.length > 0)
return errors;
}

schema.statics.create = function (data) {

let errors = await checkIfDatabaseHasUsersWithSameNameAndEmail(); <== ERROR: await is a reserved word

if (errors)
throw new Error(errorMessages);

let company = new this(data);
return company.save();
}

运行时,我在代码中发现以下错误:await is a reserved word

这是我第一次使用 async/await,所以可能我的做法是错误的。我的目标是按顺序运行唯一的测试(findOne),如果一切顺利,则保存新的寄存器。

最佳答案

错误是因为您试图等待某些内容,但尚未声明函数异步。我没有用 Mongoose 测试这个,但它看起来像这样。

async function checkIfDatabaseHasUsersWithSameNameAndEmail(data) {
const uniques = ['name', 'email'];
return Promise.all(uniques.map(async (field) => {
const query = {};
query[field] = data[field];
query.deleted = false;
return model.findOne(query);
}));
}

schema.statics.create = async function create(data) {
try {
const results = await checkIfDatabaseHasUsersWithSameNameAndEmail(data);
results.forEach((result) => {
console.log(`Here's the issue: ${JSON.stringify(result)}`);
throw new Error('Do something about it.');
});

const company = new this(data);
return company.save();
} catch (error) {
throw error;
}
};

关于JavaScript 异步/等待 : await is a reserved word,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47044543/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com