0

I'm trying to return a value from a function with a Promise, but I keep getting undefined,

export const checkForAgent = (language, country) => {
  return new Promise((resolve, reject) => {
    jsonp(
      `https://example.com/status?language=${language}&country=${country}`,
      null,
      (err, data) => {
        if (err) {
          console.error(err.message);
          reject("There was a problem!");
        } else {
          resolve(data.status);
        }
      }
    );
  });
};

I'm calling the promise as follows:

const status = checkForAgent("de", "ch");
console.log("status: ", status);

and in the console I'm getting

status:  Promise {<pending>}

I need to just get data.status from this function,

any help would be appreciated.

akano1
  • 40,596
  • 19
  • 54
  • 67
  • 3
    what are you getting back ? How are you calling this promise ? Looks fine.. – Pogrindis Jan 13 '20 at 13:13
  • What you have is fine. It returns a promise. To use the result, you have to consume the promise, e.g.: `checkForAgent("de", "ch").then(result => { /*...use result here...*/}).catch(error => { /* ...handle/report error here... */});`. See the [linked question](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call)'s answers for details, and [MDN's promises page](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises). – T.J. Crowder Jan 13 '20 at 13:15
  • Is it possible to get the result from the same function? – akano1 Jan 13 '20 at 13:16
  • Please see the answers to the [linked question](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) and, again, the [MDN promises page](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises). – T.J. Crowder Jan 13 '20 at 13:16

0 Answers0