2

I want to edit a res.json what callbacked(Promise.then) result is to associative array like this "{category:"tennis",data:res.json()}"

then I want to get a it without a Promise type

I tried it but It returned with Promise Type

const promise = new Promise(function(resolve,reject) {
  fetch("http://localhost:100/api/v1/categories/map").then(response
    => resolve(response.json()))
});





promise.then(value => Promise.all(value.category.map(
  category => {
     return (fetch("http://localhost:100/api/v1/categoriescategory=tennis"))
  }
))
.then(responses => {console.log(responses);
  return Promise.all(responses.map(res=> {
     console.log(res.json()) <- this is not Promise
  return(
  {category:"tennis",data:res.json()}  <- this is  Promise


)
} )
)}))
.then(value=>console.log(value)) // {{category:"tennis",Promise{data:data}} <- i want to unwrap Promise

Naoya
  • 77
  • 2
  • 9
  • thatis my mistake, So I am going to edit it!! – Naoya May 31 '19 at 05:13
  • You can completely replace the first part with `const promise = fetch("http://localhost:100/api/v1/categories/map").then(response => response.json())` because fetch already returns a promise and that's how promises work – slebetman May 31 '19 at 05:14
  • Unless each call of `categoriescategory=tennis` returns something different, it looks like you're mapping the `value.category` array, but you're not using any of its values? The `category` variable is going unused. Is that intended? Sounds like you might just make *two* requests, not one request followed by a request for every item in `category` – CertainPerformance May 31 '19 at 05:23
  • Someone is actually using `resolve` as `resolve` and not `fulfill` :O – Benjamin Gruenbaum May 31 '19 at 09:13

1 Answers1

1

Because fetch returns a Promise, and consuming that Promise with .json() (or .text(), etc) gives you another Promise, you need to call .then twice; put another .then in your initial mapping function, just like you're doing with your initial const promise. You should also avoid the explicit promise construction antipattern:

const promise = fetch("http://localhost:100/api/v1/categories/map").then(response => response.json());

promise.then(value => Promise.all(value.category.map(
  category => {
    return fetch("http://localhost:100/api/v1/categoriescategory=tennis")
      .then(response => response.json());
      // ^^^^^^^^^^^^^^^^^^^^^^^^^
  }
))
.then(responseObjects => {
  return Promise.all(responseObjects.map(responseObject => {
    return {
      category: "tennis",
      data: responseObject
    }
  }))
}))
  .then(value => console.log(value))
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320