react native pormise.all with deviceinfo and geolocation



我正在构建我的第一个反应原生应用程序,我正在使用DeviceInfo(react-native-device-info(和地理位置API。

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

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

他们都在回报承诺。如何将它们与类似promise.all()的东西合并

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

在这里检查GetMacAddress的API,getCurrentPosition不使用promises,而是使用回调,它的api在这里。

您可以使用Promise.all做的是,您可以将getCurrentPosition包装到承诺中,然后将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
})

最新更新