How to use async await or promise instead of timer?

Baidu map used. Must first use Baidu map to get the target location and use Baidu map to get the target location, and then through Baidu map to get me and the target location. Due to asynchronous reasons, so I used a timer to solve, but the performance is certainly not good, how to use async await or promise instead of timer?

the code snippet is as follows:

    // 
    var myGeo = new BMap.Geocoder();
    //  
    myGeo.getPoint(scope.targetname, function(point){
        if (point) {
            scope.target = point;
        }else{
            toast("!");
        }
    }, scope.cityname);


// 
    var geolocation = new BMap.Geolocation();
    geolocation.getCurrentPosition(function(r){
        if(this.getStatus() == BMAP_STATUS_SUCCESS){
            // alert(":"+r.point.lng+","+r.point.lat);
            
            scope.myadd = new BMap.Point(r.point.lng,r.point.lat);
             // console.log(scope.myadd,"")
        }
        else {
            alert("");
        }        
    },{enableHighAccuracy: true})
    


   
    
// 

    setTimeout(function(){
        if(scope.myadd!=""&&scope.target!=""){
          
            var map = new BMap.Map("l-map");
            map.centerAndZoom(new BMap.Point(scope.target.lng,scope.target.lat), 11);
            var walking = new BMap.WalkingRoute(map, {renderOptions: {map: map, panel: "r-result", autoViewport: true}});
            walking.search(scope.myadd, scope.target);
        }
    }, 1000);
Mar.16,2021

you can encapsulate the geolocation into a method that returns a promise object, and then the address parsed externally uses asny,await to fetch the geolocation method, so you can implement Synchronize.


to put it simply, do this (the following is pseudocode):


    
    
    
    // ,
    // 
    var myGeo = new BMap.Geocoder();
    let promiseTarget = new Promise((resolve)=>{
        myGeo.getPoint("", function(point){
            if (point) {
                resolve(point)
            }else{
                alert("!");
            }
        }, "");
    })


    

    var geolocation = new BMap.Geolocation();
    let promiseLocation = new Promise((resolve)=>{
        geolocation.getCurrentPosition(function(r){
            if(this.getStatus() == BMAP_STATUS_SUCCESS){
                resolve(r.point)
            }
            else {
                alert('failed'+this.getStatus());
            }        
        },{enableHighAccuracy: true})
    })


    Promise.all([promiseTarget,promiseLocation]).then(([target,location])=>{
        console.log(target,location,5)
            // API
        var map = new BMap.Map("allmap");
        map.centerAndZoom("",12);  //,
        alert(':'+(map.getDistance(target,location)).toFixed(2)+' ');  //,
        var polyline = new BMap.Polyline([target,location], {strokeColor:"blue", strokeWeight:6, strokeOpacity:0.5});  //
        map.addOverlay(polyline);     //
    })


</script>
Menu