创建新记录时如何在 sails 中使用 "await"
How to use "await" in sails when creating a new record
我想用"await"
根据 sails 文档,我的行为如下:
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
我应该怎么做才能解决这个问题。
我认为你应该让你的函数异步。
async(function(){
var new_place = await Place.create({...})
})();
如果您正在使用 await,则不应使用回调。您应该按照说明管理回复 here
Also you can check this guide of how to manage async in sail.js
SyntaxError: await is only valid in async function
这是因为您在 async
以外的函数中使用了 await
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.
您需要使函数 async
生效。在您的代码中进行这些更改,
'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 });
}
},
我想用"await"
根据 sails 文档,我的行为如下:
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
我应该怎么做才能解决这个问题。
我认为你应该让你的函数异步。
async(function(){
var new_place = await Place.create({...})
})();
如果您正在使用 await,则不应使用回调。您应该按照说明管理回复 here
Also you can check this guide of how to manage async in sail.js
SyntaxError: await is only valid in async function
这是因为您在 async
await
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.
您需要使函数 async
生效。在您的代码中进行这些更改,
'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 });
}
},