首先,我是Java语言的初学者,所以如果我的信息有任何不确定性或不确定性,请随时纠正我。
我尝试创建一个操作来支持我的IBM Watson Assistant。调用后,该操作应从http获取一些信息,并提供一些答案。
“获取”操作是Webhook的一部分,已通过Heroku成功部署,以支持Dialogflow。我只是稍作更改,以使答案更容易。
function main(req){
const http = require('http');
const API_KEY = '85324cac';
const prodname = req.prodname;
const reqUrl = encodeURI(`http://www.omdbapi.com/?t=${prodname}&apikey=${API_KEY}`);
http.get(reqUrl, (responseFromAPI) => {
let completeResponse = '';
responseFromAPI.on('data', (chunk) => {
completeResponse += chunk;
});
responseFromAPI.on('end', () => {
const movie = JSON.parse(completeResponse);
let dataToSend = prodname ;
dataToSend += (typeof movie.Title === "undefined") ? `Sorry the film is not in our database` : `${movie.Title} is a ${movie.Actors} starer ${movie.Genre} movie, released in ${movie.Year}. It was directed by ${movie.Director}.`;
return {answer: dataToSend};
});
});
//return {answer: dataToSend};
}
我期待“返回”操作后得到答案,但是它只显示空值。我很确定该操作永远不会进入“ http.get”部分。当删除//和调用代码时,它返回以下消息:“ dataToSend未定义”;如果我按原样保留代码(带有注释),则不会弹出错误。
omdapi是免费的,但在美国托管,以防万一。
有什么想法吗?无论如何,请先谢谢。
答案 0 :(得分:0)
认为您会发现在返回对omdbapi的外部调用之前,ibm函数已完成。您最好的选择是使用Promise(是全新的,我希望您可能还没有使用Promise-建议阅读https://cloud.ibm.com/docs/openwhisk?topic=cloud-functions-creating-javascript-actions#creating-javascript-actions
不是您的完整程序,请给您一些帮助;
function main(req){
const http = require('http');
const API_KEY = '85324ca';
//const prodname = req.prodname;
const prodname = 'Game%20of%20Thrones&Season=1';
const reqUrl = 'http://www.omdbapi.com/?t=Game%20of%20Thrones&Season=1&apikey=85324cac';
//const reqUrl = encodeURI(`http://www.omdbapi.com/?t=${prodname}&apikey=${API_KEY}`);
return new Promise(function(resolve, reject) {
http.get(reqUrl, (responseFromAPI) => {
let completeResponse = '';
responseFromAPI.on('data', (chunk) => {
completeResponse += chunk;
// you could return answer here via resolve.
//var parsedData = JSON.parse(completeResponse);
//console.log(parsedData);
//resolve(parsedData);
})
responseFromAPI.on('error', (error) => {
console.log(error);
reject(error);
})
responseFromAPI.on('end', () => {
var parsedData = JSON.parse(completeResponse);
console.log(parsedData);
resolve(parsedData);
});
});
});
}