Ajax异步不返回值

时间:2019-12-16 05:54:07

标签: javascript jquery ajax

我被困在这一点上,任何人都可以帮我解决这段代码!! ...这是一个异步点,在获取值尝试使async: false之前返回,但无法获取返回值。

function Routing(){
    var from= document.getElementById("from").value;
    var to =document.getElementById("to").value;

    var fromcoordinates=coordinates(from);
    var tocoordinates=coordinates(to);

    console.log(fromcoordinates);
}
function coordinates(values){
 var cords;
    $.ajax({
         url: 'https://geocoder.ls.hereapi.com/6.2/geocode.json',
         type: 'GET',  
         dataType: 'jsonp',
         async : false,
         jsonp: 'jsoncallback',

         data: {
           searchtext: values,
           gen: '9',
           apiKey: 's_WF6U2g60ucHbmnYIyuieeUWnkT0jshGf4mD33kpwI'
         },
         success: function (data) {

          var x = JSON.parse(JSON.stringify(data));
          cords=[x.Response.View[0].Result[0].Location.DisplayPosition.Latitude, x.Response.View[0].Result[0].Location.DisplayPosition.Longitude];
          console.log(cords);
         }

       });
    console.log(cords);
    return cords;
      }

1 个答案:

答案 0 :(得分:0)

在函数执行并返回success之后,将触发cords回调。相反,您可以将coordinates包裹在promise中,然后使用Promise.all

function Routing(){
    var from= document.getElementById("from").value;
    var to =document.getElementById("to").value;

    var fromcoordinates=coordinates(from);
    var tocoordinates=coordinates(to);

    Promise.all([fromcoordinates, tocoordinates]).then(values => {
        // values[0] = from
        // values[1] = to
        console.log(values[0]);
        console.log(values[1]);
    });
}

function coordinates(values) {
    return new Promise((resolve, reject) => {
        $.ajax({
         url: 'https://geocoder.ls.hereapi.com/6.2/geocode.json',
         type: 'GET',  
         dataType: 'jsonp',
         async : false,
         jsonp: 'jsoncallback',

         data: {
           searchtext: values,
           gen: '9',
           apiKey: 's_WF6U2g60ucHbmnYIyuieeUWnkT0jshGf4mD33kpwI'
         },
         success: function (data) {

          var x = JSON.parse(JSON.stringify(data));
          // Resolve the promise with the coordinates
          resolve([x.Response.View[0].Result[0].Location.DisplayPosition.Latitude, x.Response.View[0].Result[0].Location.DisplayPosition.Longitude]);
         }

       });
    });
}