簡體   English   中英

反應中異步函數中意外的保留字“等待”

[英]Unexpected reserved word 'await' in async function in react

我真的是 React 新手,我想獲取位置坐標並將它們傳遞給帶有參數的 API,但我收到:

 Unexpected reserved word 'await'

代碼:

  async getData() {
if (navigator.geolocation) {
  navigator.geolocation.watchPosition(function (position) {
    console.log("Latitude is :", position.coords.latitude);
    console.log("Longitude is :", position.coords.longitude);

    var lat = position.coords.latitude;
    var lon = position.coords.longitude;

    const url = `http://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=ca148f5dc67f12aafaa56d1878bb6db2`;
    const response = await fetch(url);
    let data = await response.json();
    
    console.log(data);
  });
}

}

您的await不在async函數中(它在嵌套在async函數中的非async函數中),但更大的問題是您的getData試圖為不符合承諾模型的內容返回承諾:來自地理定位對象的重復系列更新。 watchPosition重復調用它的回調,而不僅僅是一次。

JavaScript 沒有針對此類事物的內置語義,這通常稱為“可觀察的”(好吧,有async迭代器,但我懷疑您可能不想要那樣)。 有它的庫,但否則你必須讓getData接受一個回調,只要有更新就會被調用。 類似的東西:

getData(callback) {
    if (!navigator.geolocation) {
        throw new Error("No geolocation available");
    }
    navigator.geolocation.watchPosition(position => {
        console.log("Latitude is :", position.coords.latitude);
        console.log("Longitude is :", position.coords.longitude);

        var lat = position.coords.latitude;
        var lon = position.coords.longitude;

        const url = `http://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=ca148f5dc67f12aafaa56d1878bb6db2`;
        fetch(url)
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP error ${response.status}`);
            }
            return response.json();
        })
        .then(result => {
            try {
                callback(result);
            } catch { }
        })
        .catch(error => {
            // ...perhaps handle the error or similar...
        });
    });
}

從名稱getData來看,您可能只是想一次性獲取當前位置。 這就是getCurrentPosition方法。 如果是這樣,您將需要手動創建一個承諾,因為getCurrentPosition不提供:

getData() {
    return new Promise((resolve, reject) => {
        if (!navigator.geolocation) {
            reject(new Error("No geolocation available"));
            return;
        }
        navigator.geolocation.getCurrentPosition(position => {
            console.log("Latitude is :", position.coords.latitude);
            console.log("Longitude is :", position.coords.longitude);

            var lat = position.coords.latitude;
            var lon = position.coords.longitude;

            const url = `http://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=ca148f5dc67f12aafaa56d1878bb6db2`;
            resolve(
                fetch(url)
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`HTTP error ${response.status}`);
                    }
                    return response.json();
                })
            );
        });
    });
}

但這僅當您只想要當前位置時。

該函數需要是async 您確實將父函數設為異步,但隨后您還傳入了一個未設為異步的回調

  async getData() {
if (navigator.geolocation) {
  navigator.geolocation.watchPosition(async function (position) {
    console.log("Latitude is :", position.coords.latitude);
    console.log("Longitude is :", position.coords.longitude);

    var lat = position.coords.latitude;
    var lon = position.coords.longitude;

    const url = `http://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=ca148f5dc67f12aafaa56d1878bb6db2`;
    const response = await fetch(url);
    let data = await response.json();
    
    console.log(data);
  });

暫無
暫無

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

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