为什么我的函数返回一个 Promise { <pending> } 而不是我的条目?

Why is my function returning a Promise { <pending> } instead of my entries?

问题:

我想 return 从某个位置到某个范围(公里)的公司。 这些公司位于当前包含 2 个测试条目的数据库中。 除此之外,我还使用Google的距离矩阵API来计算距离。

在它没有工作之后,调试告诉我函数 returns[Promise {<pending>}, Promise {<pending>}].

代码:

const
    axios = require("axios"),
    knex = require('knex')(require('../knexfile'));

const getAllByDistance = (location) =>
    knex('companies')
        .select()
        .then(entries =>
            entries.map(company =>
                getDistance(location, `${company.street}, ${company.postcode} ${company.place}`)
                    .then(distance => {
                        knex('companies')
                            .select()
                            .where(parseInt(company.maximum_distance_km) >= parseInt(distance.toString().slice(0, -3)))
                    }))
        );

const getDistance = async (loc1, loc2) => {
    const origins = encodeURI(`?origins=${loc1}`);
    const destinations = encodeURI(`&destinations=${loc2}`);
    const key = `&key=${process.env.VUE_APP_GOOGLE_MAPS_API_KEY}`;
    const config = {
        method: 'get',
        url: `https://maps.googleapis.com/maps/api/distancematrix/json${origins}${destinations}${key}`,
        headers: {}
    };
    return await axios(config)
        .then((response) => {
            return response.data['rows'][0]['elements'][0]['distance'].value;
        })
        .catch((err) => {
            console.log(err);
        });
}

带调试的函数调用:

companyService
        .getByDistance(location)
        .then(companies => {
            console.log(companies)
            res.status(200);
            res.json(companies);
        })
        .catch(err => {
            res.status(500);
            res.end(`Error: ${err.message}`);
        });

我建议您从全面 async/await 而不是 then().

的混合开始

getDistance 方法开始:

const getDistance = async (loc1, loc2) => {
    const origins = encodeURI(`?origins=${loc1}`);
    const destinations = encodeURI(`&destinations=${loc2}`);
    const key = `&key=${process.env.VUE_APP_GOOGLE_MAPS_API_KEY}`;
    const config = {
        method: 'get',
        url: `https://maps.googleapis.com/maps/api/distancematrix/json${origins}${destinations}${key}`,
        headers: {}
    };
    try{
        const response = await axios(config)
        return response.data['rows'][0]['elements'][0]
    }
    catch(e){
        console.log(e);
        // return 0; // What should we return if there's an error?
    }            
}

现在,getAllDistances 方法变得 很多 更易于管理,无需所有嵌套(警告:我对 knex 一无所知,我只是按照您的代码进行操作正如我评论的那样,您反复查询所有公司似乎很奇怪....但试图复制我认为您拥有的相同功能)

const getAllByDistance = async (location) => {
   const entries = await knex("companies").select();

   const results = [];
   for(let i=0;i<entries.length;i++){
       const company = entries[i];
       const distance = await getDistance(location, `${company.street}, ${company.postcode} ${company.place}`);

       const result = await knex('companies')
                            .select()
                            .where(parseInt(company.maximum_distance_km) >= parseInt(distance.toString().slice(0, -3)));
        results.push(result);
   }
   return results;
}

上面有一些缺点,主要是它按顺序通过原始公司列表获取距离,然后加载该距离内的所有公司 - 但它会让你开始使用更有效的算法我'我确定。