javascript - 对对象使用 Promise

标签 javascript react-native es6-promise

是否可以使用 Promise 进行 object 迭代? 这是我的源代码。

 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));

上面的代码不起作用,因为我在 object.keys.map 函数中使用了 Promise。

为了获得正确的数组结果,我想我必须使用 Promise for Object.map

我已经使用 PromiseArrays 进行 Promise 迭代,但它不起作用。

有没有最好的解决办法?

最佳答案

注意,return没有值编辑自.map()console.log(array)Promise 之外调用链。您可以使用Promise.all()并从 .map() 返回一个值获得一组已满足的 Promise对象位于 .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));

关于javascript - 对对象使用 Promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46598782/

相关文章:

javascript - 关于{长度: } provided below的困惑

c# - MVC 中的数据模板 :- how to define constant in javascript from the c# code

javascript - react native : update state then check with addListener

ios - native 动画模块不可用 - react native

javascript - 您可以在创建 Promise 后添加 .then 吗?

JavaScript、获取、API

javascript - 无法让 jQuery 隐藏工作

javascript正则表达式匹配路径深度

javascript - React-Native 不使用导航器传递 props?

javascript - 是否可以克隆 ES6 promise ?