【问题标题】:react native pormise.all with deviceinfo and geolocation使用 deviceinfo 和 geolocation 对本机 promise.all 做出反应
【发布时间】:2018-11-03 10:27:06
【问题描述】:

我正在构建我的第一个 react 本机应用程序,我正在使用 DeviceInfo (react-native-device-info) 和地理定位 API。

DeviceInfo.getMACAddress(mac => console.log(mac);

navigator.geolocation.getCurrentPosition(position => console.log(position)

他们俩都在兑现承诺。如何将它们与 promise.all() 之类的东西合并

【问题讨论】:

    标签: react-native promise


    【解决方案1】:

    好吧,我研究了你的代码,但你所做的不叫承诺,你客观地给函数一个回调,而不是使用.then来解决承诺。

    检查 GetMacAddress here 的 API 并且 getCurrentPosition 不使用承诺,而是使用回调,api 在这里。

    使用Promise.all 可以做的是,您可以将getCurrentPosition 包装到一个promise 中,然后将promise.all 与DeviceInfo 一起使用。

    getposition 包装成一个承诺:

    const getPosition = (options) => {
      return new Promise((resolve, reject) => {
        navigator.geolocation.getCurrentPosition(resolve, reject, options);
      });
    }
    

    现在像这样使用Promise.all

    const getData = async () => {
            const [macAddress, currentPos] = await Promise.all([
                DeviceInfo.getMACAddress(),
                getPosition(),
            ]);
    
            // use macAddress and currentPosition here.
    }
    

    现在macAddresscurrentPosgetMACAddressgetCurrentPosition 函数的输出。

    如果您不使用异步函数,则可以执行以下操作:

    Promise.all([
        DeviceInfo.getMACAddress(),
        getPosition(),
    ]).then((macAddress, pos) => {
        // access macAddress and pos in this func
    }).catch((error) => {
        // access any error here
    })
    

    【讨论】:

    • 这里的拒绝和解决是什么?它们的功能需要定义吗?
    • 不,这些都是每一个承诺都给出的。当一个承诺完成它的事情时,它就会解决。如果它有错误,它会拒绝。
    猜你喜欢
    • 2021-09-05
    • 2017-08-07
    • 1970-01-01
    • 2021-05-08
    • 1970-01-01
    • 1970-01-01
    • 2018-05-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多