harrissid
harrissid

Reputation: 13

How get the array back out of a function

I'm trying to get the array back out of a function with console.log(mj[0]) it is returning undefined

var ref = "somefile.json"
var mj = [];

async function ss() {
  await fetch(ref).then((respose) => {
    return respose.json();
  }).then((data) => {
    console.log(data)
    var a = Object.keys(data)
    mj.push(a)
  })
}
ss()

console.log(mj)
console.log(mj[0])

Upvotes: 1

Views: 60

Answers (1)

code-gorilla
code-gorilla

Reputation: 2438

When you run console.log(mj[0]), mj is still empty. The reason is that your function ss is executed asynchronously.

You just have to await the method call:

var ref = "somefile.json"
var mj = [];

async function ss() {
  await fetch(ref).then((respose) => {
    return respose.json();
  }).then((data) => {
    console.log(data)
    var a = Object.keys(data)
    mj.push(a)
  })
}
// You also have to await here.
await ss()

console.log(mj)
console.log(mj[0])

This will work if you use promise chaining:

async function ss() {
  return fetch(ref).then((respose) => {
    return respose.json();
  }).then((data) => {
    console.log(data)
    var a = Object.keys(data)
    mj.push(a)
  })
}

ss().then(() => console.log(mj[0]));

Upvotes: 2

Related Questions