我在使用lambda函数将数据保存到Firebase数据库中时遇到问题。超时了。我试图将超时设置为5分钟,理想情况下,该超时不应执行,但仍应超时。

'use strict';

var firebase = require('firebase');

exports.handler = (event, context, callback) => {

    console.log(context);

    var params = JSON.stringify(event);

    var config = {
    apiKey: "SECRETAPIKEY",
    authDomain: "myapplication.firebaseapp.com",
    databaseURL: "https://myapplication.firebaseio.com",
    storageBucket: "myapplication.appspot.com",
    messagingSenderId: "102938102938123"
    };

    if(firebase.apps.length === 0) {   // <---Important!!! In lambda, it will cause double initialization.
        firebase.initializeApp(config);
    }

    var db = firebase.database();

    var postData = {
    username: "test",
    email: "test@mail.com"
    };

    // Get a key for a new Post.
    var newPostKey = firebase.database().ref().child('posts').push().key;

    // Write the new post's data simultaneously in the posts list and the user's post list.
    var updates = {};
    updates['/posts/' + newPostKey] = postData;

    callback(null, {"Hello": firebase.database().ref().update(updates)}); // SUCCESS with message
};


上面的代码将数据保存在Firebase中,但超时。

如果按照Link中的说明使用context.callbackWaitsForEmptyEventLoop = false,它不会超时,但不会保存数据。

请让我知道如何解决此问题。 cloudwatch中没有有用的信息。

还有一件事,如果我将rest api用于firebase来保存数据,它将很好地工作。

最佳答案

问题是您的回调函数

callback(null, {"Hello": firebase.database().ref().update(updates)}); // SUCCESS with message


在Firebase进行更新之前被调用。

您应该将您的回调函数放在Firebase更新回调中,而不是当前的回调中:

firebase.database().ref().update(updates, function (err) {

    // your processing code here

    callback(null, {<data to send back>});
})

07-24 09:39
查看更多