0

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.

1
  • 1
    Use await getData() or getData().then(apiStatus => … Commented Mar 4, 2020 at 20:42

1 Answer 1

1

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'){
         ...
      }
});
Sign up to request clarification or add additional context in comments.

1 Comment

Using the callback ".then" did the trick! I thank you so much for the assistance!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.