Mark Locklear
Mark Locklear

Reputation: 5335

Accessing a JSON array element outside of a Javascript async function

I have the following script:

async function getJobs () {
    const response = await fetch('https://redhat.jobs/jobs/feed/json');
    json = await response.json();
    console.log("inside getJobs fuction " + json);
}

jobs = getJobs();
console.log("outside getJobs function" + jobs);

The first console.log displays the json response as I would expect. However, with the 2nd log I see outside getJobs function[object Promise] in the console.

I think what is happening here is that I need to wait for getJobs to run/complete before assigning the results to the jobs variable? Or is my approach this entirely wrong to begin with.

Just to give more context, I want getJobs to once, then I want to do stuff with the jobs array in the app.

Upvotes: 1

Views: 966

Answers (2)

jmkmay
jmkmay

Reputation: 1506

fetch(url) and response.json() both return a Promise. What you can do with Promises is use a .then() statement. This allows you to execute some code once the Promise has been resolved. With regards to your above code, you'll notice if you run it as is, you get:

"outside getJobs function[object Promise]"
"inside getJobs fuction [object Object], [object Object], ..."

This is because getJobs() returns a Promise. So:

jobs = getJobs();
console.log("outside getJobs function" + jobs);

Executes console.log() immediately after it recieves a Promise from getJobs(). It's only when that Promise is resolved that you'll get anything useful, so you want to make sure you're calling console.log() only once the Promise has been resolved.

You can do this by using a .then() statement. Learn more about them here. This allows you to treat this code synchronously. You don't even have to worry about making getJobs() async (this can make code slightly more confusing when Promise chaining does the job just fine in my opinion). I would implement above like this:

function getJobs() {
    var result = fetch('https://redhat.jobs/jobs/feed/json');
    console.log('result inside getJobs is a Promise')
    return(result)
}

getJobs().then(function(response){
  return response.json();
  })
  .then(function(jobs){
  console.log('result after promise chain is ' + jobs)
  }
);

Upvotes: 2

Scott Picquerey
Scott Picquerey

Reputation: 74

You need to create another async function in which you call getJobs() with await. The reason you have outside getJobs function[object Promise] is because the console.log is ran before the promise being resolved.

Doing it this way will fix your issue :

async function run(){
  async function getJobs () {
      const response = await fetch('https://redhat.jobs/jobs/feed/json');
      json = await response.json();
      return(json);
  }

  jobs = await getJobs();
  console.log(jobs);
 }
 
 run();

Upvotes: 0

Related Questions