异步函数用forEach时提前返回,获Pending Promise,如何获取tax值?
解决异步函数返回Pending Promise及遍历问题的方案
问题根源分析
你的代码存在两个核心问题:
- 异步函数调用方式错误:
accessSpreadsheet是异步函数,它本质会返回一个Promise对象,直接用console.log打印必然得到Pending状态的Promise——因为此时异步操作还没完成,结果还未生成。 - 遍历逻辑可优化:虽然
forEach是同步遍历(不会导致提前返回),但用它来查找匹配项不够高效,换成find方法能更简洁精准地获取目标行。
修正后的完整代码
async function accessSpreadsheet(orderId) { let tax = ""; const doc = new GoogleSpreadsheet('54345u7iJzvl59oeyT_9np1Xd2_54654656'); await promisify(doc.useServiceAccountAuth)(creds); const info = await promisify(doc.getInfo)(); const sheet = info.worksheets[0]; const rows = await promisify(sheet.getRows)({ offset: 1 }); // 用find替代forEach,找到匹配项后立即停止遍历,更高效 const targetRow = rows.find(row => orderId === row.orderid); if (targetRow) { tax = targetRow.imei1; } return tax; } // 正确调用异步函数的两种方式: // 方式1:用async/await(需在async函数内执行) async function getTaxResult() { try { const taxValue = await accessSpreadsheet("88280"); console.log(taxValue); } catch (err) { console.error("获取表格数据失败:", err); } } getTaxResult(); // 方式2:用.then()链式调用 accessSpreadsheet("88280") .then(taxValue => console.log(taxValue)) .catch(err => console.error("获取表格数据失败:", err));
关键细节说明
- 正确处理Promise:异步函数必须通过
await(仅在async函数内部可用)或者.then()来获取最终结果,否则只能拿到未完成的Promise对象。 - 优化遍历逻辑:
find方法会在找到第一个匹配项后立即终止遍历,相比forEach遍历整个数组更高效,代码逻辑也更直观。 - 添加错误处理:建议通过
try/catch或.catch()捕获异步操作中可能出现的错误(比如认证失败、网络异常、表格不存在等),避免程序意外崩溃。
内容的提问来源于stack exchange,提问作者Ashwani Panwar
相关产品推荐
相关产品推荐

