簡體   English   中英

如何從承諾中獲得結果值?

[英]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

有人可以向我解釋從承諾中獲取價值的正確方法是什么嗎? 謝謝

您需要使用回調方法而不是在getGeolocation()函數中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);
    }
});

要了解回調是如何工作的,請訪問以下鏈接,您將有一個更好的主意。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM