简体   繁体   English

类型错误:未定义不是函数 - Cloud Functions 中的 Promise.all() 错误

[英]Type error: undefined is not a function - Promise.all() error in Cloud Functions

I am trying to fetch the document ID's of all the users in my database.我正在尝试获取数据库中所有用户的文档 ID。 For which I have written this code:我为此编写了这段代码:

exports.scheduledFunction = functions.pubsub
  .schedule('every 2 minutes')
  .onRun(async context => {
    console.log('This will be run every 2 minutes!');
    try {
      const usersRef = await admin //Works Perfectly, I get the QuerySnapshot of the collection
        .firestore()
        .collection('Users')
        .get();
      console.log('usersRef: ', usersRef);
      const userDocs = await Promise.all(usersRef); //This gives the error
      console.log('User Docs: ', userDocs);
    } catch (err) {
      console.log('err: ', err);
    }
    return null;
  });

I obtain this error on passing the QuerySnapshot promise in Promise.all() :我在Promise.all()传递 QuerySnapshot 承诺时Promise.all()此错误:

//Error
TypeError: undefined is not a function
    at Function.all (<anonymous>)
    at exports.scheduledFunction.functions.pubsub.schedule.onRun (/srv/index.js:624:38)
    at <anonymous>
    at process._tickDomainCallback (internal/process/next_tick.js:229:7)

I expected to collect all the document IDs from the result of Promise.all()我希望从Promise.all()的结果中收集所有文档 ID

Help would be very much appreciated.非常感谢帮助。

Promise.all() takes an array of promises. Promise.all()接受一组承诺。 usersRef is neither an array, nor a promise. usersRef既不是数组,也不是承诺。 Since you're already awaited the promise returned by get(), that makes usersRef a QuerySnapshot object that's immediately available, so you will need to work with it on those terms.由于您已经在等待 get() 返回的承诺,这使得usersRef成为一个立即可用的QuerySnapshot对象,因此您需要根据这些条件使用它。 Since it's a snapshot and not a reference , you should probably name it differently.由于它是快照不是参考,您可能应该对其进行不同的命名。 For example:例如:

const usersSnapshot = await admin
        .firestore()
        .collection('Users')
        .get();

const usersDocs = usersSnapshot.docs
console.log(usersDocs)

usersSnapshot.forEach(doc => {
    console.log(doc)
})

The await Promise.all is not needed, since you already load all user documents int the first statement with get() and await .不需要await Promise.all ,因为您已经使用get()await将所有用户文档加载到第一个语句中。

So it should be:所以应该是:

  const usersDocs = await admin 
    .firestore()
    .collection('Users')
    .get();
  console.log('User Docs: ', userDocs);

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

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