即使在回调中定义变量后,变量仍未定义

Getting undefined for a variable even after defining it in a callback

我通过使用 google-distance-matrix API 将以下代码用于 Google 地图的距离矩阵 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"]

另外,我不想发送距离,计算距离后还有一些其他操作。

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

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

你的问题的原因是因为异步执行而你没有等待它。事情是这样的:

// 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放在的回调里面=13=]:

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
});