How to use “await” in sails when creating a new record

送分小仙女□ 提交于 2019-12-04 01:53:03

问题


I want to use "await"

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});
 }
},  

But I get the following Error:

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.


回答1:


SyntaxError: await is only valid in async function

This is because you are using await in a function that is not async

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.

Source MDN async function

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 });
        }
    },



回答2:


I think you should make your function async.

 async(function(){
   var new_place = await Place.create({...})
})();

And if you are using await you should not use callbacks. You should manage the response as explained here

Also you can check this guide of how to manage async in sail.js



来源:https://stackoverflow.com/questions/49594267/how-to-use-await-in-sails-when-creating-a-new-record

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!