-2

I have the program below:

const request = require('request');
var res = {};
process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = 0
res = adpost();
//console.log(res.body);
console.log(res.body);

async function adpost() {
  var postResponse = await Post();
  return postResponse;
}
async function Post() {
  const options = {
    url: "xxx",
    form: {
      'usenumber': ''
    }
  };

  return new Promise((resolve, reject) => {
    request(options, (error, response, body) => {
      if (error) {
        return resolve({
          body,
          error
        });
      }

      return resolve({
        body,
        response
      })
    });
  })
}

As it returns the promise, I tried to call in another async function as well. I always get a pending promise or undefined. How will I get the actual value?

Michael M.
  • 10,486
  • 9
  • 18
  • 34
  • 2
    Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – jonrsharpe Jan 16 '20 at 20:05
  • EVERY `async` function returns a promise. You have to use `.then()` or `await` on a return value from an `async` function to get the resolved value. That's how `async` works. – jfriend00 Jan 16 '20 at 20:34

1 Answers1

0

adpost is an asynchronous function. It takes some time to run, does not return immediately, and the code does not wait for it to return before continuing executing statements. res = adpost(); does not wait for the request to finish before assigning the value. You can't make synchronous code (like the top level of your file, where res = adpost(); is) grab asynchronous results.

You must use a callback or another asynchronous function. There isn't a way to get the response body up into synchronous context, you can only pass around a Promise or a callback that will be resolved/executed when the response body is available.

const request = require('request');
adpost().then(res => {
    console.log(res.body);
});
Klaycon
  • 10,599
  • 18
  • 35