0

我在回调之外访问值有问题,我有一个如下所示的 json

[ { Latitude: '3.59288601404616',
    Longitude: '98.6827551573515',
    Latitude1: '3.5828173285855724',
    Longitude1: '98.69136337190866',
  },
   { Latitude: '3.65865664490563',
     Longitude: '98.6652326211333',
     Latitude1: '3.5828173285855724',
     Longitude1: '98.69136337190866',
  } ]

我读过很多网络说不可能从回调中获取价值,因为我们必须先等到回调完成,然后我们才能获得价值,stackoverflow 中的一些问题提供了一些解决方案,但没有人适合我。

我想要得到的是在我上面发布的那个 json 中添加一个新的 json,我想在里面添加 Distance json 所以我使用node-google-distance

我想要的是这样的

[ { Latitude: '3.59288601404616',
    Longitude: '98.6827551573515',
    Latitude1: '3.5828173285855724',
    Longitude1: '98.69136337190866',
    Distance '10127'
  },
   { Latitude: '3.65865664490563',
     Longitude: '98.6652326211333',
     Latitude1: '3.5828173285855724',
     Longitude1: '98.69136337190866',
     Distance: '1836'
  } ]

我的代码是这样的

models.xxxx.findAll({
    where: {
        UserId: req.params.UserId
    },
    attributes: ['Latitude', 'Longitude', [sequelize.literal('(SELECT Latitude FROM `xxxx` WHERE `id` = ' + req.params.MerchantId + ')'), 'Latitude1'],
        [sequelize.literal('(SELECT Longitude FROM `xxxx` WHERE `id` = ' + req.params.MerchantId + ')'), 'Longitude1']
    ]
}).then(function(lists) {

    var json = JSON.parse(JSON.stringify(lists));

    function get_count(item, callback) {
        var array = [];
        for (var i = 0; i < json.length; i++) {
            distance.get({
                    origin: json[i].Latitude1 + ',' + json[i].Longitude1,
                    destination: json[i].Latitude + ',' + json[i].Longitude
                },
                function(err, data) {
                    if (err) {
                        array.push(0);
                    } else {
                        array.push(data.distanceValue);
                    }

                    item.distanceValue = array;
                });
        }
        callback(null, item);
    }
    async.map(json, get_count, function(err, results) {
        console.log(results);
    });
});

我使用async.map是因为在这个网络上有人发布了 Javascript: return a value to a variable outside of a callback function,我花了很多时间在 stackoverflow 中搜索,但什么也没找到

NodeJS无法访问回调内部的变量

如何从异步回调函数返回值?

NodeJS 获取异步返回值(回调)

站点 1

站点 2

请给我一些提示或一些示例如何解决此问题

4

0 回答 0