如何从承诺中获得结果价值?

我无法从promise函数返回地理位置坐标。我正在使用下面的代码,从这里开始:How geolocation.getCurrentPosition return value?

const getPosition = () => {
  return new Promise((res,rej) => {
      navigator.geolocation.getcurrentPosition(res,rej)
  });
}

export const getGeolocation = () => {
  getPosition().then(console.log)
}

我尝试过:

export const getGeolocation = () => {
  return getPosition().then(result => return result)
} // doesnt work

有人可以向我解释从诺言中获得价值的正确方法是什么?谢谢

zhuzheqi2096409 回答:如何从承诺中获得结果价值?

您需要使用回调方法代替return函数中的getGeolocation()

这是您的解决方案:

export const getGeolocation = (callback) => {
  getPosition().then((result) => {
     callback(result);
  })
}

现在请看下面的代码,以访问来自getPosition()函数的结果。

getGeolocation((result)=>{
   console.log("Position : ",result);
});

请检查以下代码,希望它对您和

都适用

const getPosition = () => {
    return new Promise((res,rej) => {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(res);
        } else {
            rej("Unable to found current location");
        }

    });
}

export const getGeolocation = (callback) => {
    getPosition().then((result) => {
        callback({
            code: 1,message: "Location",location: result
        });
    }).catch((_error) => {
        callback({
            code: 0,message: _error
        });
    });
}

getGeolocation((response) => {
    if (response.code == "1") {
        console.log(response.location);
    } else {
        console.log(response.message);
    }
});

要了解回调的工作方式,请通过下面的链接,您将会有一个更好的主意。

https://www.w3schools.com/jquery/jquery_callback.asp

,

尝试一下。

const getPosition = () => {
    return new Promise((res,rej) => {
        navigator.geolocation.getCurrentPosition(res,rej)
    });
}
const getGeolocation = async() => {
    try {
        let result = navigator.permissions.query({
            name: 'geolocation'
        });
        if (result.state == 'granted') {
            let respnse = await getPosition();
        } else {
            throw new Error("User denied Geolocation");
        }
    } catch (error) {
        console.log(error.message);
    }
}
getGeolocation();

本文链接:https://www.f2er.com/2727864.html

大家都在问