如何从sails控制台调用助手?

问题描述 投票:0回答:1

我试图在sails.js中创建一个helloworld助手(示例here

我的文件是get.js和sails将帮助函数命名为get()

get.js文件:

module.exports = {

  friendlyName: 'Format welcome message',

  description: 'Return a personalized greeting based on the provided name.',

  inputs: {

    name: {
      type: 'string',
      example: 'Ami',
      description: 'The name of the person to greet.',
      required: true
    }

  },

  fn: async function (inputs, exits) {
    var result = `Hello, ${inputs.name}!`;
    return exits.success(result);
  }

};

但是当我在风帆控制台中制作它时

await sails.helpers.get("john")

它返回一个错误:

SyntaxError: await is only valid in async function

我无法找到错误的位置,或者是否有错误。什么可能是错的?提前致谢

sails.js helper
1个回答
0
投票

你看到的错误是因为你只能从另一个await函数中async函数的返回。如果你“直接从控制台”调用代码,它会像你看到的那样爆炸。

为了快速测试/修补,您可以使用.then()从控制台中获取助手的返回值

sails.helpers.get("john").then(console.log).catch(console.error)
sails.helpers.get("john").then((greeting) => {
  console.log('Got greeting:', greeting)
}).catch(console.error);

或者,通过将辅助调用包装在异步IIFE中,然后使用await

(async () => {
  let greeting = await sails.helpers.get("john")
  console.log(greeting)
})();
© www.soinside.com 2019 - 2024. All rights reserved.