skip to Main Content

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


  1. Chosen as BEST ANSWER

    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:

    const https = require('https');
    
    async function fetchData() {
      try {
        var yyy;
        const data = await postNode('yyyyxxxhello world 9999', 'nothing here', '356', '3');
        yyy = data;
        return yyy; // Return the value of yyy
      } catch (error) {
        console.error(error);
        throw error;
      }
    }
    
    fetchData()
      .then((yyy) => {
        console.log(yyy); // Access the value of yyy outside the async function
      })
      .catch((error) => {
        console.error(error);
      });
    
    function postNode(title, body, parent, page) {
      return new Promise((resolve, reject) => {
        // ...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);
            resolve(data);
          });
        });
    
        request.on('error', (error) => {
          console.error('Error:', error);
          reject(error);
        });
    
        request.write(postData);
        request.end();
      });
    }
    

  2. Once you are in asynchronous land, you need to stay there. You can either:

    1. Add callback to your own function, so the caller of your function can pass their callback.
    2. Convert this to promises so you can await the function
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search