【问题标题】:How to use "await" in sails when creating a new record创建新记录时如何在风帆中使用“等待”
【发布时间】:2018-04-01 02:32:55
【问题描述】:

我想用“等待”

根据 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  

我应该怎么做才能解决这个问题。

【问题讨论】:

    标签: node.js sails.js


    【解决方案1】:

    SyntaxError: await 仅在异步函数中有效

    这是因为您在不是async 的函数中使用了await

    请记住,await 关键字仅在异步函数中有效。如果你在异步函数体之外使用它,你会得到一个 SyntaxError。

    来源 MDN async function

    您需要创建函数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 });
            }
        },
    

    【讨论】:

      【解决方案2】:

      我认为你应该让你的函数异步。

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

      如果您正在使用 await,则不应使用回调。您应该按照here

      的说明管理响应

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

      【讨论】:

      • 非常感谢,这是一个很好的提示,您还介绍了很好的参考资料
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-15
      • 1970-01-01
      • 2019-01-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多