[英]IBM Cloud Function produce no output
I have some troubles while running this IBM Cloud Function:运行此 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);
});
}
My problem is that the first invokes of this function (at least the first 3-4) produce no output.我的问题是此函数的第一次调用(至少前 3-4 次)不产生任何输出。 The subsequent calls run properly and the log is correctly shown.
后续调用正常运行,日志正确显示。 How can I fix this unpredictable behaviour?
我该如何解决这种不可预测的行为? I'd like, of course, to retrieve my data at first call of this function.
当然,我想在第一次调用这个函数时检索我的数据。 Thanks.
谢谢。
Node.js uses an non-blocking asynchronous programming model. Node.js 使用非阻塞异步编程模型。 This
main
function returns before the HTTP response is available.此
main
函数在 HTTP 响应可用之前返回。
Returning a Promise will allow you to wait on the HTTP response.返回 Promise 将允许您等待 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 })
});
})
}
Two additional things to check:需要检查的另外两件事:
.json
to your endpoint.json
附加到您的端点https://<ibm-domain>/api/v1/web/<username>/default/<function>.json
https://<ibm-domain>/api/v1/web/<username>/default/<function>.json
Enable as Web Action
in the Endpoints
sidebar menu.Endpoints
侧边栏菜单中选择Enable as Web Action
。 Also, you should be able to return an async
main function in lieu of the Promise
object.此外,您应该能够返回一个
async
主函数来代替Promise
对象。
async function main(params) {
try {
// some `await` function
} catch (e) {
// catch `await` errors
}
}
module.exports = main;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.