我定义了一些变量,我使用它们来检索工作的lat&lng,但是在我将变量传递给另一个函数后,它不起作用

问题描述 投票:1回答:1

我面临的问题如下。

我在函数中使用关键字var x = 0创建一些变量;在某些时候,我为x分配一个新值,然后我将它记录到控制台,它显示正确的值。但是当我尝试使用x(新值)将其与字符串/链接连接时,我得到0而不是新值。

我试图离开x而没有0,之后说是undefined。我错在哪里?

尝试:var x;其中x = 0;

在第一个场景中,它将是未定义的,在第二个场景中将为0。

    geocode();
    function geocode() {

    var lng = 0;
    var lattitude = 0;
    var lattitudeb = 0;
    var lngb = 0;

    var locationA = '1234';
    var locationB = '1323';

    axios.get('https://maps.googleapis.com/maps/api/geocode/json', {
        params: {
            address: locationA,
            key: 'AIzaSyBpHiHzK323fsregSMCDbgX33xAUB_Cwwi8'
        }
    }).then(function (response) {

        lattitude = response.data.results[0].geometry.location.lat;
        lng = response.data.results[0].geometry.location.lng;


       console.log(lattitude);
       console.log(lng);
    }).catch(function (error) {
        console.log(error);
        });

    axios.get('https://maps.googleapis.com/maps/api/geocode/json', {
        params: {
            address: locationB,
            key: 'AIzaSyBpHiHzK3434fdf3434rferfeX33xAUB_Cwwi8'
        }
    }).then(function (response) {

        lattitudeb = response.data.results[0].geometry.location.lat;
        lngb = response.data.results[0].geometry.location.lng;

        console.log(lattitudeb);
        console.log(lngb);
    }).catch(function (error) {
        console.log(error);
    });

    axios.get('https://maps.googleapis.com/maps/api/distancematrix/json', {
        params: {
            units: 'imperial',
            origins: lattitude + ',' + lng, // here i get always 0 instead 
                                               of the new updated value
            destinations: lattitudeb + ',' + lngb,
            key: 'AIzaSyBpHirfserfserfser434efddf3ISMCDbgX33xAUB_Cwwi8'
        }
    }).then(function (r) {
        console.log(r);
    }).catch(function (e) {
        console.log(e);
    });

}
javascript variables scope int var
1个回答
1
投票

这三个要求:

    axios.get('https://maps.googleapis.com/maps/api/geocode/json', {
    axios.get('https://maps.googleapis.com/maps/api/geocode/json', {
    axios.get('https://maps.googleapis.com/maps/api/distancematrix/json', {

正在同时发送。第三个在第一个接收纬度和其他东西之前消失。此时,lattitude的价值仍为零。

这就是为什么你应该:发送第一个,.then根据其输出发送一个。好的做法是将所需的数据作为第一个promise的返回值传递,而不是使用外部变量。

实际上,在这里,#3依赖于#1和#2的结果,而#1和#2是独立的,我正在读它吗?因此,正确的模式将是

Promise.all([
//... first request here
//... second request here
])
.then(
//... third request here
© www.soinside.com 2019 - 2024. All rights reserved.