問題:
我想從某個位置回傳某個范圍(公里)的公司。這些公司位于當前包含 2 個測驗條目的資料庫中。除此之外,我還使用 Google 的距離矩陣 API 來計算距離。
在它不起作用后,除錯顯示該函式回傳[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}`);
});
uj5u.com熱心網友回復:
我建議你從全面開始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;
}
以上有一些缺點,主要是它依次遍歷獲得距離的原始公司串列,然后加載該距離內的所有公司 - 但我相信它會讓你開始使用更有效的演算法。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/374102.html
標籤:javascript 节点.js 异步 异步javascript 膝关节
上一篇:異步抓取網站時編碼錯誤
