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

如何在Promise链中传递guestPlayerIds数组?代码返回undefined问题

解决guestPlayerIds返回undefined的问题

嘿,我看了你的代码,问题出在Promise链式调用的返回值上——你的第一个.then()处理完guestPlayerIds后没有把它返回,所以下一个.then()自然拿不到值,只能得到undefined。咱们来看看两种最佳的解决方式:

方式1:修正Promise链式调用的返回逻辑

在第一个.then()里处理完数组后,一定要把guestPlayerIds返回出去,这样下一个.then()才能接收到正确的结果。另外,你原来用map()遍历但没用到返回的新数组,换成forEach()会更合适:

exports.sendNewEventFcm = functions.database.ref('/fcm/{pushID}').onWrite(event => { 
  const eventID = event.params.pushID; 
  const dsnap = event.data.val(); 

  // Exit when the data is deleted. 
  if (!event.data.exists()) { 
    return; 
  } 

  let guests = Object.keys(dsnap); 
  const promises = guests.map((data) => admin.database().ref('playerIds').child(data).once('value')); 

  return Promise.all(promises).then(data => { 
    let guestPlayerIds = []; 
    // 用forEach替代map,因为我们只需要遍历处理,不需要生成新数组
    data.forEach(item => { 
      let itemVal = Object.keys(item.val())[0]; 
      console.log(itemVal);
      guestPlayerIds.push(itemVal); 
    }); 
    // 关键:把处理好的数组返回给下一个then
    return guestPlayerIds; 
  }).then(guestPlayerIds => { 
    console.log(guestPlayerIds); // 现在就能拿到正确的数组了
  }); 
});

方式2:用async/await简化代码(更推荐)

如果你的运行环境支持ES2017及以上,用async/await可以彻底避免Promise链式调用的嵌套问题,代码会更直观易读:

exports.sendNewEventFcm = functions.database.ref('/fcm/{pushID}').onWrite(async (event) => { 
  const eventID = event.params.pushID; 
  const dsnap = event.data.val(); 

  // Exit when the data is deleted. 
  if (!event.data.exists()) { 
    return; 
  } 

  let guests = Object.keys(dsnap); 
  const promises = guests.map((data) => admin.database().ref('playerIds').child(data).once('value')); 
  
  // 用await等待所有Promise完成,直接拿到结果
  const data = await Promise.all(promises); 
  
  let guestPlayerIds = []; 
  data.forEach(item => { 
    let itemVal = Object.keys(item.val())[0]; 
    console.log(itemVal);
    guestPlayerIds.push(itemVal); 
  }); 
  
  console.log(guestPlayerIds); // 直接访问变量,不需要链式then
});

核心原因就是Promise的链式调用规则:每个.then()的参数都是上一个.then()的返回值。如果上一个.then()没有return任何值,默认就会返回undefined,这就是你遇到的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 07:12:17