我是js和async / await的新手,我想使用yandex maps api建立距离矩阵,然后使用ACO算法优化路线。一切正常,但是由于等待循环中的每个请求,我的距离矩阵生成了这么长时间。我知道我应该避免这种情况,但我不知道如何。
我的距离矩阵应该在调用ACO算法函数之前完成。
async function buildDistanceMatrix(ymaps) {
const n = routeCoords.length;
let distanceMatrix = [];
console.log(routeCoordsRef.current);
for (let i = 0; i < n; i++) {
let newArr = [];
for (let j = 0; j < n; j++) {
await ymaps.route([routeCoordsRef.current[i], routeCoords[j]]).then((route) => {
newArr.push(route.getLength())
console.log(i, j, routeCoordsRef.current[i], routeCoords[j], route.getLength());
});
}
distanceMatrix.push(newArr);
}
return distanceMatrix;
}
let distanceMatrix = await buildDistanceMatrix(ymaps);
// and here my distance matrix done and i'm calling another function that uses distanceMatrix
我认为您需要考虑以下两个注意事项...
注意1:通常在处理Promise时,请使用“ async” /“ await”或坚持使用“ .then()”语法,但不要混合使用它们。例如...
async function buildDistanceMatrix(ymaps) {...
let route = await ymaps.route( [ routeCoordsRef.current[ i ], routeCoords[ j ] ] );
newArr.push( route.getLength() );
console.log( i, j, routeCoordsRef.current[ i ], routeCoords[ j ], route.getLength() );
...}
...要么...
function buildDistanceMatrix(ymaps) {...
ymaps.route( [ routeCoordsRef.current[ i ], routeCoords[ j ] ] ).then( ( route ) => {
newArr.push( route.getLength() );
console.log( i, j, routeCoordsRef.current[ i ], routeCoords[ j ], route.getLength() );
} );
...}
一般来说,“ async” /“ await”更具可读性,因为它提供了按过程读取的语法,并有助于避免嵌套then()
函数。
注2: Yandex路由器功能似乎利用了Web服务...
...因此需要诺言,因为Yandex服务器响应后,JavaScript代码实际上会暂停等待诺言得以解决。
建议研究Promise.all()函数...
...这样一来,您的职能部门就可以发起许多承诺,而无需等待任何承诺的完成,只有创建了所有承诺后,您的职能才等待所有承诺的解决。
主要好处是远程服务器可以同时处理所有请求。
在沿着这条路径运行之前,请检查Yandex服务条款,以确定并发未完成呼叫的数量是否受到限制。此外,设计良好的Web服务将限制并发请求的数量,因此少量的Web调用可能会在性能上有较大的提高,但是在达到一定限制后,Web服务器的限制就会启动,然后将调用实质上排队(或忽略!)并再次同步处理...
编辑:使用Promise.all和async / await语法。
简而言之,函数在创建Promise时不应等待,而应将Promise捕获到数组中。然后,一旦创建了所有承诺(在这种情况下,将发起一系列Web服务调用),然后等待该Promise.all()
函数,并传递所有未解决的承诺。产生的数组将直接与承诺的传递顺序相对应Promise.all()
。通常是您的函数外观。请注意增加了parallelArray,这是一种在以后使用arrayOfResults时捕获所需的任何辅助数据的方法。
async function buildDistanceMatrix(ymaps) {...
let arrayOfPromises = [];
let parallelArray = [];
for ( let i = 0; i < n; i++ ) {
for (let j = 0; j < n; j++ ) {
arrayOfPromises.push( ymaps.route( [ routeCoordsRef.current[ i ], routeCoords[ j ] ] ) );
parallelArray.push( { i: i, j: j, rci: routeCoordsRef.current[ i ], rcj: routeCoords[ j ] );
}
}
let arrayOfResults = await Promise.all( arrayOfPromises );
...}
希望这可以帮助...
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句