【问题标题】:Firebase Cloud Function - How can I solve this error: ECONNRESETFirebase 云功能 - 如何解决此错误:ECONNRESET
【发布时间】:2021-01-25 21:59:32
【问题描述】:

这是我的代码

const functions = require('firebase-functions');
const admin = require('firebase-admin');
const axios = require('axios');
admin.initializeApp(functions.config().functions);

exports.sendNotifications = functions
.region('europe-west1')
.pubsub.schedule('every day 04:00').onRun(async context => {

    axios.get('http://niksimoni.pythonanywhere.com/api/pulizie_domani')
    .then(listOfStreets => {
        const streets = listOfStreets.data.strade;
        const promises = [];
        for (const street of streets) {
            const p = axios.get('http://niksimoni.pythonanywhere.com/api/data_pulizie?indirizzo=' + street)
            .then(listOfHours => {
                const ora = listOfHours.data.ora;
                var topic = street.split(" ").join("-");
                var message = {
                    data: {
                        title: street,
                        subtitle: 'Pulizia domani alle ' + ora,
                    },
                    topic: topic
                };
                admin.messaging().send(message)
                .then((response) => {
                    // Response is a message ID string.
                    console.log('Successfully sent message:', response);
                })
                .catch((error) => {
                    console.log('Error sending message:', error);
                });
            })
            promises.push(p);
        }
        return Promise.all(promises);
    })
    .catch(error => {
        console.log(error);
    });
  });

我尝试将 axios 替换为请求,但它并没有解决问题,无论我更改什么,我总是收到此错误:'发出请求时出错:客户端网络套接字在建立安全 TLS 连接之前已断开连接。错误代码:ECONNRESET' 我试图学习如何处理承诺,我以为我理解它,但也许我错了。 任何帮助将不胜感激

【问题讨论】:

    标签: javascript node.js firebase google-cloud-functions firebase-cloud-messaging


    【解决方案1】:

    始终在云函数中返回承诺:

    return axios.get('http://niksimoni.pythonanywhere.com/api/pulizie_domani')
    

    还有这个:

    return admin.messaging().send(message)
    

    否则,云函数会突然终止正在执行的代码。你可能也想对你的 catch 块做同样的事情。你可以在这里阅读更多信息:https://firebase.google.com/docs/functions/terminate-functions

    【讨论】:

    • 我是否必须保留这个返回语句:return Promise.all(promises);?
    • 是的。即使您错过了 Promise 链中的一个 return 语句,也不能保证该代码堆栈在云函数中执行。
    • 不幸的是,即使进行了这些更改,我也遇到了同样的错误......
    • 返回响应: return admin.messaging().send(message) .then((response) => { return response; }) 并查看响应是否在输出中打印为数组从“TESTING”(console.cloud.google.com/functions/details/us-central1/…)执行它
    • 另外,在问题中添加您的新代码,以便我查看。
    猜你喜欢
    • 1970-01-01
    • 2020-04-27
    • 1970-01-01
    • 2020-03-27
    • 2018-11-17
    • 2022-06-25
    • 2013-11-17
    • 1970-01-01
    • 2021-12-01
    相关资源
    最近更新 更多