Seth0080
Seth0080

Reputation: 157

Using Return Value from Async Function In IF Statement

New to NodeJS and JavaScript

I am using NodeJS to make an API call to return some JSON data within an async function. Presently, the API call is working as intended and I have parsed the data that I am looking for. The trouble I am having is using that parsed json data as a condition within an IF statement so I can continue along with the rest of the scripts intended functions. To simplify for the mean time I have written it to display a string statement if the JSON data is what I expect it to be:

const fetch = require("node-fetch");
var accessToken = "Bearer <ACCESS TOKEN>";
var url = '<API ENDPOINT>';
var headers = {
    'Content-Type': 'application/json',
    'Accept': 'application/json',
    'Authorization': accessToken
};

const getData = async url => {
    try {
        const response = await fetch(url, {method: "Get", headers: headers});
        const json = await response.json();
        console.log(json.status);
        return json.status
    } catch (error) {
        console.log(error);
    }

};

let apiStatus = getData(url);
let activated = "ACTIVATED";
let configured = "CONFIGURED";

if (apiStatus.toString() !== activated) {
    console.log("BLAH");
}

Essentially, if the return value of "json.status" is equal to "ACTIVATED", then I will perform an action. Else, I will perform a different action.

At present, I am unable to use the output of the "getData()" to be used in an IF condition. Any assistance with next steps would be appreciated.

Upvotes: 0

Views: 1034

Answers (1)

alex067
alex067

Reputation: 3281

You need to wait for the promise to be resolved, because right now you'd be evaluating a Promise (pending) object.

Your getData() function is fine.

let apiStatus = await getData(url);

I don't think async works on the window scope, you can try this out. If this doesn't work, then you just need to wait for the promise to be resolved.

getData(url).then(
   status => {
      if (status.toString() === 'activated'){
         ...
      }
});

Upvotes: 1

Related Questions