【问题标题】:sails.js http.get and callback functions?sails.js http.get 和回调函数?
【发布时间】:2018-05-01 06:53:42
【问题描述】:

我是 Javascript async 和 Sails.js 的新手,我觉得我误解了一些概念。

我有一个函数试图进行 HTTP GET 调用以从 URL 获取 cmets 作为 JSON,然后解析这些 cmets 以提供一个“分数”对象来对用户 cmets 进行评分。我的代码示例如下 -

fn: async function (inputs, exits) {
let commentsUrl = 'http://foobar.com';

// we want to return a score of the users comments
let score = {};

// callback function that calls a helper to score comments
let processComments = async function (error, result) {
  let scored = await sails.helpers.scoreComments(result);
  return scored;
}

let HTTP = require('machinepack-http');

// go get JSON data of user comments
HTTP.get({
  url: commentsUrl,
  data: {},
  headers: {}
}).exec((err, result) => score = processComments(err, result)
);

// this should be awaiting for the processComments callback to finish?
return exits.success(score);

我的问题可能很明显 - 函数在回调完成执行之前立即返回,并且 score 的值只是 {}。我已经尝试过将 HTTP.get 调用更改为 --

// go get JSON data of user comments
HTTP.get({
  url: commentsUrl,
  data: {},
  headers: {}
}).exec((err, result) => score = await processComments(err, result)
);

但这会导致编译错误,指出sails 不理解processComments 回调前面的'await' 关键字。

我误解了什么?我想将 'scored' 的值返回给 main 函数,并觉得我应该'等待'一些东西,但我不确定在哪里。

【问题讨论】:

    标签: javascript http async-await sails.js


    【解决方案1】:

    await 关键字仅适用于 Promise,从您使用的库 (machinepack-http) 的文档来看,它们似乎不适用于 Promise。

    您可以尝试切换到基于 Promise 的库,例如 axios,或者将 machinepack 的请求转换为 Promise,如下所示:

    function getComments() {
        return new Promise((resolve, reject) => {
            HTTP.get({
                url: commentsUrl,
                data: {},
                headers: {}
            }).exec((err, result) => {
                if (err) {
                    return reject(err);
                }
                resolve(result);
            });
        });
    }
    

    那么你就可以在 fn 里面使用这个了:

    score = processComments(await getComments());
    
    return exits.success(score);
    

    【讨论】:

      【解决方案2】:

      我想到我应该做的是回调中的响应--

      fn: async function (inputs, exits) {
      let commentsUrl = 'http://foobar.com';
      
      // callback function that calls a helper to score comments
      let processComments = async function (error, result) {
      let scored = await sails.helpers.scoreComments(result);
        return return exits.success(scored);
      }
      
      let HTTP = require('machinepack-http');
      
      // go get JSON data of user comments
      HTTP.get({
       url: commentsUrl,
       data: {},
        headers: {}
      }).exec((err, result) => score = processComments(err, result)
      );
      
      // return nothing here
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-06-02
        • 2017-12-20
        • 1970-01-01
        • 1970-01-01
        • 2020-03-22
        • 1970-01-01
        • 2014-07-30
        • 1970-01-01
        相关资源
        最近更新 更多