即使在回调中定义了变量,也会对其进行未定义



我使用google-distance-matrixAPI为谷歌地图的距离矩阵API使用以下代码。代码如下:

app.get("/users", (req, res) => {
// console.log(req.query);
// res.send(req.query);
const origins = [`${req.query.origin}`];
const destinations = [`${req.query.dest}`];
var dist;
let carbonEstimate;
try {
// distance matrix calculation
distance.matrix(origins, destinations, (err, distances) => {
// console.log("Calculating distance...");
if (err) {
console.log(err);
res.status(404).send("Error");
return;
}
if (!distances) {
res.send("No distance calculated");
return;
}
dist = distances.rows[0].elements[0].distance.text.split(" ");
console.log(dist);
});
console.log(dist);
res.send("OK");
}
catch(err) {console.log(err); res.send("ERROR");}
});

对于相距320公里的有效始发地和目的地,控制台上的输出如下:

undefined
["320", "km"]

此外,我不想发送距离,在计算距离后还会进行一些其他操作。

我知道它是异步创建的,但我不知道如何修复它。我该怎么办?

问题的原因是异步执行,而您没有等待它

// you define GET /users route, and whenever someone enters it, the callback is executed
app.get("/users", (req, res) => {
// console.log(req.query);
// res.send(req.query);
const origins = [`${req.query.origin}`];
const destinations = [`${req.query.dest}`];
var dist;
let carbonEstimate;
try {
// distance matrix calculation
// here you call ASYNC method (distance.matrix), which might take some time to execute
// it's result would be handled with the callback
// so js CONTINUES with the next line
distance.matrix(origins, destinations, (err, distances) => {...});
// here you print dist, but since the callback for distance.matrix
// is NOT yet called (operation not done), the value is undefined
console.log(dist);
// you're sending the response BUT distance is not yet calculated
res.send("OK"); // <-- MOVE this
}
catch(err) {console.log(err); res.send("ERROR");}
});

如果您想发回距离,则必须res.send放入distance.matrix:的回调

distance.matrix(origins, destinations, (err, distances) => {
// console.log("Calculating distance...");
if (err) {
console.log(err);
res.status(404).send("Error");
return;
}
if (!distances) {
res.send("No distance calculated");
return;
}
dist = distances.rows[0].elements[0].distance.text.split(" ");
console.log(dist);
res.send("OK"); // -- you send the response AFTER distance calculated
});

每个请求只能发送一个响应。由于res.send("OK")位于回调代码之外,它将首先运行并完成请求,这意味着回调永远不会发生。

相关内容

  • 没有找到相关文章

最新更新