简体   繁体   中英

Async function in javascript doesn't wait for the result?

my problem is that I want that my second function wait for the end of the exection of the first function, (i want the first point, before call the routing) but that seems not working. I'am quite new to coding with this, and i would appreciate any help and advise.

the code is:

async function waitForLoc(){
    if(navigator.geolocation){
        navigator.geolocation.getCurrentPosition(function(position){
            latUser = (position.coords.latitude) ;
            lngUser = (position.coords.longitude);
            var marker = L.marker([latUser, lngUser]).addTo(mymap);
        })
    }else console.log("geolocation does not work");
    return 1;
}
waitForLoc();

lat = coordinates[1];
lng = coordinates[0];

async function f() {
    let promise = new Promise((resolve, reject) => {
    setTimeout(() => resolve("done!"), 1000)
    });

    let result = await promise; 

    if(Route){
        mymap.removeControl(Route);
    }

    Route = L.Routing.control({
        waypoints: [
            L.latLng(latUser, lngUser),
            L.latLng(lat, lng)
        ],
        routeWhileDragging: false
    }).addTo(mymap);

    mymap.closePopup();
}
f();

The async keyword allows you to use await inside a function and, as a side effect, forces that function to return a promise.

It doesn't detect the presence of a callback and automatically promisify that. You have to do that manually . If you do that then you can just return that promise, there is no point is using async unless you are await ing something.

It doesn't cause code outside itself to automatically await the promise it returns. Again, you have to do that explicitly.

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