Home > Software engineering >  Mapping items fetched from API javascript
Mapping items fetched from API javascript

Time:04-06

I am trying to map some items returned to me from a API using a class and constructor with javascript.

My question is what I am doing wrong, since the log before the mapping "Result before Map" logs out my array of items. But after my map I get nothing and everything in my constructor is undefined.

class Test {
  constructor(obj) {
    this.testValue = obj.testValue
  }
}

async function getItems() {
  const promises = []

  const response = (await fetch(url)).json()
  promises.push(response)

  const result = await Promise.all(promises)
  console.log('Result before Map:', result)
  const tests = result.map(test => new Test(test))
  console.log('Result after Map:', tests)
}

CodePudding user response:

You have one too many "await"s in there.

async function getItems() {
    const promises = []
    promises.push(fetch(url));

    const result = await Promise.all(promises)
        .map((r) => r.json());
    console.log('Result before Map:', result)
    const tests = result.map((t) => new Test(t))
    console.log('Result after Map:', tests)
}

The question is where "url" comes from. Currently there is no reference to url and even if, then it is just a single url. Maybe you're looking for something like:

async function getItems(urls) {
    const promises = urls.map((u) => fetch(u));
    const result = await Promise.all(promises)
        .map((r) => r.json());
    console.log('Result before Map:', result)
    const tests = result.map((t) => new Test(t))
    console.log('Result after Map:', tests)
}

CodePudding user response:

With a single url, it would just be

async function getItem(url) {
    const result = await fetch(url);
    const resJSON = result.json()
    console.log('Result before Map:', resJSON)
    const test = new Test(resJSON);
    console.log('Result after Map:', test)
}
  • Related