为什么Firestore调用get方法返回Promise而非直接返回对应值
问题原因
- Firebase 提供的
get()是原生异步接口,所有云端读写相关的操作默认返回Promise对象,不会同步返回计算结果。 - 示例代码中
return customerID是写在forEach的回调函数内,该返回值仅会终止当前循环,并不会作为then回调的返回值向外传递,因此外层赋值的customer123永远是get()方法返回的Promise实例。 - JavaScript 执行时同步代码优先级高于异步微任务,外层的
console.log(customer123)执行时,get()的网络请求还未完成、回调逻辑还未触发,自然无法拿到预期的结果值。
解决方法
方案1:使用async/await语法(推荐)
用async/await简化异步逻辑写法,同时用数组find方法替代forEach解决返回值传递问题:
// 封装为异步函数 async function getCustomerId(businessNameValue) { const snapshot = await db.collection('CustomerDatabase').get() const matchedDoc = snapshot.docs.find(doc => businessNameValue === doc.data().BusinessName) return matchedDoc ? matchedDoc.data().CustomerID : null } // 调用方式1:在其他async函数内用await接收 const customer123 = await getCustomerId('目标商户名') console.log(customer123) // 调用方式2:用then链式接收 getCustomerId('目标商户名').then(customer123 => { console.log(customer123) // 所有依赖customer123的业务逻辑都放在此处执行 })
方案2:使用Promise链式调用
如果有特殊场景不想用async/await,也可以直接在then链内处理结果:
let customer123 = null db.collection('CustomerDatabase').get().then((snapshot) => { snapshot.forEach((doc) => { if(businessNameValue === doc.data().BusinessName){ customer123 = doc.data().CustomerID } }) }).then(() => { console.log(customer123) // 后续业务逻辑放在此处执行 })
性能优化建议
不需要拉取全表数据后再遍历筛选,可以直接在查询时加where条件过滤,大幅提升请求性能:
const snapshot = await db.collection('CustomerDatabase').where('BusinessName', '==', businessNameValue).get()
内容的提问来源于stack exchange,提问作者RoniDoni
相关产品推荐
相关产品推荐

