Node.js中如何将distance计算结果从函数作用域中正确返回
问题根因
这是Node.js中异步回调执行时序的典型问题:distance.matrix是异步API,你传入的回调函数会在距离查询的IO操作完成后才执行,但外层的getLocation函数不会等待回调执行,会直接往下执行return result,这时候回调还未触发,result还没被赋值就被返回了。另外你当前写的try/catch只能捕获同步执行阶段的报错,异步回调内部的错误无法被捕获,且原代码中res变量不在当前作用域,错误处理逻辑本身也有问题。
解决方案
方案1:改用回调形式传递结果
不要让函数直接return值,给函数新增回调参数,拿到结果后通过回调传递:
cartSchema.methods.getLocation = function (destinations, origins, callback) { try { distance.matrix(origins, destinations, function (err, distances) { if (err) return callback(err); callback(null, distances); }); } catch (e) { callback(e); } }; // 调用示例 getLocation(destinations, origins, function(err, distances) { if (err) { return res.status(500).json({ message: err.message }); } // 此处可正常拿到距离结果 console.log(distances); })
方案2:封装为Promise(更推荐,适配现代异步语法)
把异步逻辑包装成Promise返回,外层可以通过async/await更简洁地获取结果:
cartSchema.methods.getLocation = function (destinations, origins) { return new Promise((resolve, reject) => { distance.matrix(origins, destinations, function (err, distances) { if (err) return reject(err); resolve(distances); }); }) }; // 调用示例(必须在async函数内使用) async function handleDistanceQuery() { try { const distances = await getLocation(destinations, origins); // 此处可正常拿到距离结果 console.log(distances); } catch (e) { res.status(500).json({ message: e.message }); } }
内容的提问来源于stack exchange,提问作者Abdulmalek
相关产品推荐
相关产品推荐

