如何使用“等待"在创建新记录时在航行中 [英] How to use "await" in sails when creating a new record
问题描述
我想使用等待"
根据sails文档,我的行为如下:
https://sailsjs.com/documentation/reference/waterline-orm/models/创建
According to the sails documentation I act as follows:
https://sailsjs.com/documentation/reference/waterline-orm/models/create
create: function (req, res, next) {
var new_place = await Place.create({...}, function place_created(err, XX){
if(err && err.invalidAttributes) {
return res.json({'status':false, 'errors':err.Errors});
}
}).fetch();
if(new_place){
console.log(new_place);
res.json({'status':true,'result':new_place});
}
},
但我收到以下错误:
var new_place = await Place.create({...}, function place_created(err, XX){
^^^^^
SyntaxError: await is only valid in async function
我该怎么做才能解决这个问题.
what should I do to fix this.
推荐答案
语法错误:await 仅在异步函数中有效
SyntaxError: await is only valid in async function
这是因为您在不是 async
请记住,await 关键字仅在异步函数中有效.如果你在异步函数的主体之外使用它,你会得到一个 SyntaxError.
Remember, the await keyword is only valid inside async functions. If you use it outside of an async function's body, you will get a SyntaxError.
来源 MDN 异步功能
您需要使函数 async
才能工作.在您的代码中进行这些更改,
You need to make the function async
for it to work. Making those changes in your code,
'use strict';
create: async function(req, res, next) {
var new_place = await Place.create({ ... }, function place_created(err, XX) {
if (err && err.invalidAttributes) {
return res.json({ 'status': false, 'errors': err.Errors });
}
}).fetch();
if (new_place) {
console.log(new_place);
res.json({ 'status': true, 'result': new_place });
}
},
这篇关于如何使用“等待"在创建新记录时在航行中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!