You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js中如何等待API调用?封装函数未等待响应问题

解决Google Geocode API异步封装的问题

嘿,我完全懂你的困扰——这就是新手常碰到的异步回调时序问题!咱们一步步捋清楚:

问题根源

你原来的代码在路由里能正常运行,是因为你直接把res.json()放在了Geocode API的回调函数里,Express会自动等待这个异步回调执行完再响应客户端。但当你把这段逻辑封装成独立函数callGoogleGeocode后,函数本身会立刻执行完毕,根本没等Google的API响应回来——因为maps.geocode是异步操作,回调函数要等API返回结果才会触发,这时候你的函数早就结束了,自然拿不到想要的结果。

解决方案:用Promise封装异步操作

咱们把callGoogleGeocode改成返回一个Promise,这样就能用async/await或者.then()来等待API响应:

封装后的函数

function callGoogleGeocode(address) {
  // 返回一个Promise对象
  return new Promise((resolve, reject) => {
    maps.geocode({ address: address }, function (err, response) {
      if (err) {
        console.log(err);
        reject(err); // 把错误传递出去
        return;
      }
      resolve(response); // 把成功的响应传递出去
    });
  });
}

怎么使用这个函数

方式1:用async/await(推荐,代码更清晰)

在你的路由里改成异步函数:

exports.getTimeZone = async (req, res, next) => {
  try {
    // 等待API返回结果
    const geocodeResponse = await callGoogleGeocode(address);
    res.json(geocodeResponse);
  } catch (err) {
    console.log(err);
    res.status(500).json({ error: '获取地理编码失败' });
  }
}

方式2:用.then()链式调用

如果不想用async/await,也可以用Promise的链式调用:

callGoogleGeocode(address)
  .then(response => {
    // 拿到API响应后处理
    console.log('地理编码结果:', response);
    // 比如在路由里返回:res.json(response);
  })
  .catch(err => {
    // 处理错误
    console.error('请求出错:', err);
  });

额外提示

如果你用的是较新版本的@google/maps库,其实它本身已经支持Promise语法了,你可以不用手动封装——只需要调用maps.geocode().asPromise()就行,比如:

async function callGoogleGeocode(address) {
  try {
    const response = await maps.geocode({ address: address }).asPromise();
    return response;
  } catch (err) {
    console.log(err);
    throw err;
  }
}

这样代码会更简洁!

内容的提问来源于stack exchange,提问作者Alex

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:56:40