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

How to get result value out of a promise?

我无法获取从 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

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

试试这个。

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

您需要在 getGeolocation() 函数中使用 Callback 方法而不是 return

这是您的解决方案:

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

要了解回调的工作原理,请阅读以下内容link您会有更好的想法。

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