运行此IBM Cloud Function时遇到一些麻烦:
/**
*
* main() will be run when you invoke this action
*
* @param Cloud Functions actions accept a single parameter, which must be a JSON object.
*
* @return The output of this action, which must be a JSON object.
*
*/
function main(params) {
const https = require('https');
https.get('https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY', (resp) => {
let data = '';
// A chunk of data has been recieved.
resp.on('data', (chunk) => {
data += chunk;
});
// The whole response has been received. Print out the result.
resp.on('end', () => {
console.log(JSON.parse(data).explanation);
});
}).on("error", (err) => {
console.log("Error: " + err.message);
});
}
我的问题是,此函数的第一次调用(至少第一个3-4)没有输出。后续调用正常运行,并且日志正确显示。我该如何解决这种不可预测的行为?我当然希望在第一次调用此函数时检索我的数据。谢谢。
答案 0 :(得分:2)
Node.js使用非阻塞异步编程模型。此main
函数在HTTP响应可用之前返回。
返回承诺将使您能够等待HTTP响应。
function main(params) {
return new Promise((resolve, reject) => {
const https = require('https');
https.get('https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY', (resp) => {
let data = '';
// A chunk of data has been recieved.
resp.on('data', (chunk) => {
data += chunk;
});
// The whole response has been received. Print out the result.
resp.on('end', () => {
const explanation = JSON.parse(data).explanation
console.log(explanation);
resolve({ explanation })
});
}).on("error", (err) => {
console.log("Error: " + err.message);
reject({ error: err.message })
});
})
}
答案 1 :(得分:0)
要检查的另外两件事:
.json
附加到端点https://<ibm-domain>/api/v1/web/<username>/default/<function>.json
Enable as Web Action
中选择Endpoints
。此外,您应该能够返回async
主函数来代替Promise
对象。
async function main(params) {
try {
// some `await` function
} catch (e) {
// catch `await` errors
}
}
module.exports = main;