我是Javascript async和Sails.js的新手,我觉得我错误地理解了一些概念。
我有一个函数正在尝试进行HTTP GET调用以从URL获取JSON的注释,然后解析这些注释以提出一个“得分”对象来评价用户注释。我的代码示例如下 -
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);
我的问题可能很明显 - 函数在回调完成执行之前立即返回,而得分值仅为{}。我已尝试在sails中将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函数,并觉得我应该'等待'某事,但我不知道在哪里。
答案 0 :(得分:1)
await
关键字仅适用于promises,而且从您正在使用的库(machinepack-http)的文档中看,它们看起来似乎不适用于promises。
您可以尝试切换到基于Promise的库,比如axios,或者将machinepack的请求转换为Promises,如下所示:
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);
答案 1 :(得分:0)
在我看来,我应该做的是回调中的响应 -
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
}