简体   繁体   中英

Unexpected reserved word 'await' in async function in react

Im really new in React and I want to get location coordinates and pass them to API with parameters, but I receive:

 Unexpected reserved word 'await'

The code:

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

}

Your await isn't in an async function (it's in a non- async function nested in an async function), but the bigger problem is that your getData is trying to return a promise for something that doesn't fit the promise model: a repeated series of updates from the geolocation object. watchPosition calls its callback repeatedly, not just once.

JavaScript doesn't have inbuilt semantics for this kind of thing, which is generally called an "observable" (well, there are async iterators, but I suspect you probably don't want that). There are libraries for it, but otherwise you'll have to have getData accept a callback that will get called whenever there's an update. Something along the lines of:

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

From the name getData , you may have meant just to get the current location as a one-off. That's the getCurrentPosition method. If so, you'll need to create a promise manually since getCurrentPosition doesn't provide one:

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

But that's only if you want just the current location.

The function needs to be async . You did make the parent function async but then you are also passing in a callback which you didn't make asynchronous

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM