I have the following code that does a POST to an api. I put it in a function and it works and gives me a response of all the data received back for confirmation. But now I want to return the data back from the function to do something else. As seen below, I put a return in the function but it doesn’t actually return anything from the function. What could be wrong?
const https = require('https');
xxx = postNode('Hello world 9999', 'nothing here', '356', '3');
console.log(xxx);
function postNode (title, body, parent, page) {
...BUNCH OF CODE HERE...
const request = https.request(options, (response) => {
let data = '';
response.on('data', (chunk) => {
data += chunk;
});
response.on('end', () => {
console.log('Response:', data); <-- This works!
return data; <--- This Doesn't work...
});
});
request.on('error', (error) => {
console.error('Error:', error);
});
request.write(postData);
request.end();
}
2
Answers
You need to make use of Promises and the await function when working with async.
First you would need to convert your existing function into a Promise to make use of the await functionality.
Here's the updated code that would work for you:
Once you are in asynchronous land, you need to stay there. You can either:
await
the function