简体   繁体   English

在 firebase function 上运行时,我得到一个空数组,但是在手机上反应原生 expo 上运行时,我得到一个带有值的数组

[英]I'm getting an empty array when running on firebase function but an array with values when running on react native expo on phone

I have this code below that I uploaded as a firebase function.我在下面有这个代码,我作为 firebase function 上传。 whenever I checked the logs using firebase functions:log , I can see that the expoTokens array is empty.每当我使用firebase functions:log检查日志时,我可以看到 expoTokens 数组为空。

var expoTokens = [];

db.collection('members').get()
.then(docs => {

   var data = []

   docs.forEach(doc => {
      if (recipients.includes(doc.id)) {
         doc.data().expoTokens.forEach(token => {
            if (!data.includes(token)) data.push(token);
         })
      }
   })

   return Promise.all(data);
})
.then((data) => {
   expoTokens = data;
})

console.log("expoTokens");
console.log(expoTokens);

What I only need is to get an array of ExpoTokens so I can send notification.我只需要获取一个 ExpoTokens 数组,以便发送通知。

I would recommend to use asyc/await to make the code flow more clear.我建议使用asyc/await使代码流更加清晰。 Your functions could be written like this:你的函数可以这样写:

var expoTokens = [];

const docs = await db.collection("members").get();

var data = [];

docs.forEach((doc) => {
  if (recipients.includes(doc.id)) {
    doc.data().expoTokens.forEach((token) => {
      if (!data.includes(token)) expoTokens.push(token);
    });
  }
});

console.log("expoTokens");
console.log(expoTokens);

// TO DO
// Send notifications using expoTokens using await

// We return to let the cloud function know that we are done
return;

Just don't forget the async in your function like async (snap, context) => {}只是不要忘记 function 中的async ,例如async (snap, context) => {}

Your console.log(expoTokens);你的console.log(expoTokens); happens before expoTokens = data;发生在expoTokens = data; ever runs.永远运行。

See:看:

If you want to return the expo tokens out of the Cloud Function, return them from inside then upwards and out of the main function:如果您想将 expo 令牌从云 Function 退回,请从内部then向上退回主 function:

return db.collection('members').get().then(docs => {
   var data = []

   docs.forEach(doc => {
      if (recipients.includes(doc.id)) {
         doc.data().expoTokens.forEach(token => {
            if (!data.includes(token)) data.push(token);
         })
      }
   })

   return Promise.all(data);
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM