Firebase云功能console.log的奇怪问题 [英] Weird issue with firebase cloud function console.log

查看:73
本文介绍了Firebase云功能console.log的奇怪问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Firebase云功能中遇到一种情况,其中仅执行FIRST console.log或firestore update语句.

I have a situation in firebase cloud function where only FIRST console.log or firestore update statement is executed.

我还有其他类似的功能,但响应处理方式略有不同,但这没有任何问题

I have other similar function with slight variation in the way response is processed, but that does not have any issues

我已经检查了Google Cloud Console/Firebase Console等,并且源代码似乎已正确上传

I have checked google cloud console/firebase console etc and the source code seem to have been uploaded correctly

exports.myFunction = functions.firestore.document(docPath).onCreate(async (snapshot, context) => {

  var inputData = snapshot.data();
  console.log('printing request');
  console.log(inputData);

  //Prepare to call the api
  var data = {'input': 'some value'};
  var resource = 'api_resource';

  // call api - below function is provided by an external provider and takes a callback function once api call is complete

  myApi.call(resource, data.input, function (error, result) {
    if (error) {
      console.log('Error from api');
      return { status: 'error', code: 401, message: 'Error from api' }
    }

    var apiResult = JSON.parse(result);
    console.log('printing api response'); // <-- Anything below this does not get executed. When this is removed, next line is executed and so on 
    console.log(apiResult);  

    //Write to Firestore
    snapshot.ref.update({
      'status': 'computed',
    })
      .then((a) => {
        console.log('Written successfully to db');
        return 0;
      })
      .catch(err => {
        console.log('Error setting db' + err);
        return { status: 'error', code: 401, message: 'Error setting db ' }
      });

    // console.log('End of function');
    return { status: 'success', code: 200, message: 'Completed successfully' }
  });
});

我看到了另一条与此相反的帖子情况.有人知道为什么会这样吗?

I see another post that is opposite of this situation. Anyone know why this happens?

推荐答案

您需要将同步API包装在Promise中-详细信息

You need to wrap your synchronous API in a Promise - details here and here.

代码可能类似于:

exports.myFunction = functions.firestore.document(docPath).onCreate( (snapshot, context) => {

  var data = 'some value'
  var resource = 'api_resource';

  const myAPIPromise = (resource, data) => {
    return new Promise((resolve, reject) => {
      myApi.call(resource, data, (error, result) => {
        if (error) reject(error)
        else resolve(result)
      });
    })
  }

  myAPIPromise(resource, data)
  .then((result) => console.log(result))
  .catch((err) => console.log(err))

});

您显然会想要添加回所有无关的日志,并调用为清楚起见已删除的Firestore.

You'll obviously want to add back in all extraneous logs and call to Firestore which I removed for clarity.

这篇关于Firebase云功能console.log的奇怪问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆