简体   繁体   English

javascript 中的异步 function 不等待结果?

[英]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.我的问题是我希望我的第二个 function 等待第一个 function 的执行结束,(我想要第一点,在调用路由之前)但这似乎不起作用。 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. async关键字允许您在 function 中使用await ,并且作为副作用,强制 function 返回 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.如果你这样做,那么你可以只返回那个 promise,除非你正在await ,否则使用async是没有意义的。

It doesn't cause code outside itself to automatically await the promise it returns.不会导致自身外部的代码自动await它返回的 promise。 Again, you have to do that explicitly.同样,您必须明确地这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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