我正在尝试创建一个具有路由功能的应用程序,为此,我需要使用OpenRouteService。我所设定的方式是,我所设想的,在一个承诺中。
我无法将数组从承诺中提取出来,我尝试使用带有await的异步函数,但这似乎没有返回任何内容,我也不知道这个承诺是设置错了还是异步函数设置错了。
以下是承诺:
function getRoute() {
var openrouteservice = require("openrouteservice-js");
var Directions = new openrouteservice.Directions({ api_key: "######"});
// Direction Request
Directions.calculate({
coordinates: [[8.690958, 49.404662], [8.687868, 49.390139]],
profile: 'foot-walking',
extra_info: ['waytype', 'steepness'],
format: 'geojson'
})
.then(function(geojson) {
// Add your own result handling here
var PolyLine = geojson.features[0].geometry.coordinates.map(c => ({latitude: c[0], longitude: c[1]}))
console.log(PolyLine);
return PolyLine
})
.catch(function(err) {
var str = "An error occurred: " + err;
console.log(str);
});
}以下是我试图收集它的方法:
React.useEffect(() => {
async function getPolyLine() {
const res = await getRoute(); // type: Promise<Interface>
console.log(res)
setPolyLine(res);
}
getPolyLine();
}, [])
const [polyline, setPolyLine] = React.useState()我没有使用Javascript或React的实际经验,而且承诺是一个很有趣的问题。
发布于 2022-02-23 15:46:29
您需要添加如下返回语句:
function getRoute() {
var openrouteservice = require("openrouteservice-js");
var Directions = new openrouteservice.Directions({ api_key: "######"});
// Direction Request
return Directions.calculate({
coordinates: [[8.690958, 49.404662], [8.687868, 49.390139]],
profile: 'foot-walking',
extra_info: ['waytype', 'steepness'],
format: 'geojson'
})
.then(function(geojson) {
// Add your own result handling here
var PolyLine = geojson.features[0].geometry.coordinates.map(c => ({latitude: c[0], longitude: c[1]}))
console.log(PolyLine);
return PolyLine
})
.catch(function(err) {
var str = "An error occurred: " + err;
console.log(str);
});
}因此,在您的代码中,您实际上没有返回承诺。
发布于 2022-02-23 16:13:59
我认为在这里,我们必须创建我们的自定义承诺,并使用可能的值来解析它,以返回我们想要的语句的值。
在这里,我们不能像在JavaScript子句中尝试的那样,直接从内部函数返回语句。
试着做以下改变,希望它能解决你的问题:
function getRoute() {
var openrouteservice = require("openrouteservice-js");
var Directions = new openrouteservice.Directions({ api_key: "######"});
return new Promise((resolve, reject) => {
// Direction Request
Directions.calculate({
coordinates: [[8.690958, 49.404662], [8.687868, 49.390139]],
profile: 'foot-walking',
extra_info: ['waytype', 'steepness'],
format: 'geojson'
})
.then(function(geojson) {
// Add your own result handling here
var PolyLine = geojson.features[0].geometry.coordinates.map(c => ({latitude: c[0], longitude: c[1]}))
console.log(PolyLine);
resolve(PolyLine)
})
.catch(function(err) {
var str = "An error occurred: " + err;
console.log(str);
resolve([])
});
})
}https://stackoverflow.com/questions/71239918
复制相似问题