-1

I have this js code:

_fetchData = (id, callback) => {
      let url = 'https://.../id=' + id
      fetch(url)
      .then(response => response.json())
      .then(data => callback(data))
}

_addToArray = (array) => {
      let dataArray = []
      array.forEach(item => {
           _fetchData(item.id, (data) => {
                 dataArray.push(data)
           })
      }
      return dataArray
}

I want dataArray = [data1, data2, ...]

but it's dataArray = []

What' re solutions for this? Thanks a lot

justinNg
  • 21
  • 1
  • 5
  • You can write `.then(data => callback(data))` as `.then(callback)` – Robo Robok Aug 06 '21 at 20:16
  • @RoboRobok also possible to *not* pass it as a callback but return the promise and it directly to the promise chain. No need to convert a promise back to a callback solution. Promises are the *replacement* of callbacks. – VLAZ Aug 06 '21 at 20:18
  • @VLAZ also true! – Robo Robok Aug 06 '21 at 20:19

1 Answers1

0

If you don't mind using asynchronous code, since `fetch:

_fetchData = (id) => {
    return fetch(`https://.../id=${id}`)
        .then(response => response.json());
}

_addToArray = (array) => {
    return Promise.all(array.map(item => _fetchData(item.id)));
}

or simply:

_addToArray = (array) => {
    return Promise.all(array.map(item => 
        fetch(`https://.../id=${item.id}`).then(r => r.json())));
}
Kelvin Schoofs
  • 8,323
  • 1
  • 12
  • 31