0

I have a data array containing numbers and 1 object with a blob field. I walk through this array and in case the element is not a numeric value, I need to make a request and substitute a request instead of this object query result (id) How can I implement this functionality?

let data = {
  photo: [33,24, {blob: 'blob'}, 44]
}

let newData = data.photos.map ((photo, i) => {
  if (! isNaN (photo)) {
    return photo
  } else {
   //?
   let response = await fetch ('https://jsonplaceholder.typicode.com/todos/1');
   let commits = await response.json ();
   return commits.id
  }
})


console.log (newPtotoObj)

Expected result => [33,24, value_from_request, 44]

  • It is not really possible to await inside of most `Array.prototype` methods. What you could try instead, is to use `forEach`, and the callback version of `fetch`, to mutate the `data.photos` array when the callback is called. You can also wrap the whole thing in a promise. And resolve that promise when the callback resolves (so that you can `await` this promise in your calling code). – zr0gravity7 Jul 22 '21 at 05:18

1 Answers1

1

The Async/Await will not work with map as you expected. Each iteration will return a new promise. You should wait until all promises are resolved.

Why does using async-await in map function still return promises and not the resolved values?

Code Should Be:

let data = {
  photo: [33,24, {blob: 'blob'}, 44]
}

async function loadImages() {
  return await Promise.all(data.photo.map(async (photo, i) => {
    if (! isNaN (photo)) {
      return photo
    } else {
     let response = await fetch ('https://jsonplaceholder.typicode.com/todos/1');
     let commits = await response.json ();
     return commits.id
    }
  }));
}

let newData = loadImages();
BadPiggie
  • 5,471
  • 1
  • 14
  • 28