简体   繁体   中英

loadData() returning empty array

I'm trying to return an array of objects to a function, and looking at the debugger, it looks like it just returns an empty array.

Here's the function that I'm hoping to use:

// load from json file
  loadData(filepath) {
    let rooms = [];

    fetch(filepath)
      .then(
        res => res.json()
      )
      .then(function (data) {
        // console.log(data);
        for (let i = 0; i < data.rooms.length; i++) {
          rooms.push(data.rooms[i]);
        }
      });
    return rooms;
  }

I go into the debugger, and I see the rooms from data.rooms getting pushed to my local rooms object, but when I get back up to my init() function that's supposed to use this rooms data:

let rooms = this.loadData(this.datapath); // TODO: make games load from json data

    for (let i = 0; i < rooms.length; i++) {
      this.addRoom(rooms[i].name, rooms[i].getText, rooms[i].prompts, rooms[i].requirements);
    }

It looks like it's passed an empty array. Is there a scoping issue or something I'm missing? I'm not very experienced with fetch/promises/JSON.

Happy to provide any further info that may be useful. Thanks!

The problem is that your local variable rooms will be returned before the async fetch finish.

You can just simple await the fetch statements and make the function async:

async loadData(filepath) {
  let rooms = [];

  const response = await fetch(filepath);
  const data = await response.json();

  console.log(data);

  for (let i = 0; i < data.rooms.length; i++) {
      rooms.push(data.rooms[i]);
  }
  return rooms;
}

let rooms = await this.loadData(this.datapath);

Try this, if it did not work let me know.

// load from json file
async function call() {
  const loadData = async filepath => {
    let rooms = [];

    return await fetch(filepath)
      .then(res => res.json())
      .then(async data => {
        rooms = await [...data];
        return rooms;
      });
  };

  let x = await loadData("https://jsonplaceholder.typicode.com/posts");
  console.log("TEST: ", x);
}
call();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM