EN VI

How do i get the pure object out of promise object when i do promise inside promise?

2024-03-13 05:00:10
How do i get the pure object out of promise object when i do promise inside promise?

here is what i get in browser console and the code. I need first promise "starships" to get an array of url links, then i need second promise for "movieURLs" to get an object from each of that link. But when i finish it all i always get a Promise object with a pure object inside it and i need that object to access it and cannot when its in that form.

Im doing it in React.

this is what i get in console:

  1. (3) [Promise, Promise, Promise]

    1. 0: Promise

      1. [[Prototype]]: Promise

      2. [[PromiseState]]: "fulfilled"

      3. [[PromiseResult]]: Object

        1. id: 4

        2. releaseDate: "1977-05-25"

        3. title: "A New Hope"

        4. [[Prototype]]: Object

    2. 1: Promise

      1. [[Prototype]]: Promise

      2. [[PromiseState]]: "fulfilled"

      3. [[PromiseResult]]: Object

        1. id: 6

        2. releaseDate: "1983-05-25"

        3. title: "Return of the Jedi"

        4. [[Prototype]]: Object

    3. 2: Promise {<fulfilled>: {…}}

    4. length: 3

    5. [[Prototype]]: Array(0)

My code:

 PromiseAll([getStarships(user)])
            .then((result) => result[0][starshipIndex].films)
            .then((movieUrls) =>
                movieUrls.map((movieUrl: any) =>
                    getMovies(movieUrl).then((data) => data[0]),
                ),
            )
            .then((movieList) => setMovies(movieList))
            .catch((error) => console.warn(error))

I tried to use .result or .response or .response.items, but i always get undefined

Solution:

This results in a Promise:

getMovies(movieUrl).then((data) => data[0])

Which means this returns an array of Promise objects:

movieUrls.map((movieUrl: any) =>
  getMovies(movieUrl).then((data) => data[0]),
)

You can resolve those promises with a call to Promise.all, which would return a Promise that resolves to the array of results. For example:

.then((movieUrls) =>
  Promise.all(movieUrls.map((movieUrl: any) =>
    getMovies(movieUrl).then((data) => data[0]),
  ))
)

In which case the next .then() callback would get the array of results, rather than the array of Promise objects.

Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login