Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/firebase/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
已调用firebase pubsub函数,但未写入firestore_Firebase_Google Cloud Firestore_Google Cloud Functions - Fatal编程技术网

已调用firebase pubsub函数,但未写入firestore

已调用firebase pubsub函数,但未写入firestore,firebase,google-cloud-firestore,google-cloud-functions,Firebase,Google Cloud Firestore,Google Cloud Functions,我有一个简单的pub sub-cloud函数 var serviceAccount = require("./serviceAccountKey.json"); admin.initializeApp({ credential: admin.credential.cert(serviceAccount) }); exports.updateNews = functions.pubsub .topic("firebase-schedule-cronForNews-us-central1

我有一个简单的pub sub-cloud函数

var serviceAccount = require("./serviceAccountKey.json");
admin.initializeApp({
  credential: admin.credential.cert(serviceAccount)
});


exports.updateNews = functions.pubsub
  .topic("firebase-schedule-cronForNews-us-central1")
  .onPublish(message => {
    axios
      .get(
        "https://newsapi.org/v2/top-headlines?apiKey=241414&sources=espn-cric-info"
      )
      .then(result => {
        return result.data.articles.forEach(article => {
          db.collection("news").add(article);
        });
      })
      .then(result => {
        console.log(result);
        return result;
      })
      .catch(error => {
        console.log(error);
        return error;
      });

    return null;
  });

正在调用该函数,但它没有写入firestore。当我将其转换为http函数时,相同的代码可以工作。

您可以尝试返回承诺链并使用,如下所示:

exports.updateNews = functions.pubsub
  .topic("firebase-schedule-cronForNews-us-central1")
  .onPublish(message => {
    return axios  // Note the return here
      .get(
        "https://newsapi.org/v2/top-headlines?apiKey=241414&sources=espn-cric-info"
      )
      .then(result => {
        const batch = admin.firestore().batch();
        result.data.articles.forEach(article => {
           const docRef = admin.firestore().collection("news").doc();
           batch.set(docRef, article);
        });
        return batch.commit();
      })
      .then(result => {  // You don't need this then if you don't need the console.log
        console.log(result);  
        return null;
      });
  });

不客气。我建议您观看Firebase视频系列中有关JavaScript承诺的3个视频:。他们很好地解释了归还承诺链的必要性。