Search code examples
javascriptreact-nativees6-promise

Using promise for an object


Is there anyway to use promise for object iteration? Here's my source code.

 Object.keys(drop).map((key) => {
            RNGooglePlaces.lookUpPlaceByID(drop[key].placeID)
              .then((results) => {
                results.t = results.address;
                results.l = `${results.latitude},${results.longitude}`;
                array.push(results);
              })
              .catch((error) => reject(error));
 });
        console.log(JSON.stringify(array));

This code above is not working because I have used Promise in object.keys.map function.

For getting the correct result of array, I think I have to use Promise for Object.map

I have used PromiseArrays for promise iteration but it doesn't work.

Is there any best solution?


Solution

  • Note, no value is returned from .map() and console.log(array) is called outside of Promise chain. You can use Promise.all() and return a value from .map() to get an array of fulfilled Promise objects at .then()

     let promises = Promise.all(
                      Object.keys(drop).map(key => 
                        RNGooglePlaces.lookUpPlaceByID(drop[key].placeID)
                        .then(results => {
                          results.t = results.address;
                          results.l = `${results.latitude},${results.longitude}`;
                          return results;
                        })
                      )
                    );
     promises.then(results => console.log(results))
     .catch(error => console.error(error));