![](/img/trans.png)
[英]How can I return ordered data from Firebase database with Node.js using the firebase-admin module?
[英]Node.js 12.x AWS lambda does not return using firebase-admin realtime database
我已經在這個問題上卡了幾天了,幾乎沒有進展,如果可以的話,請幫忙!
I have a Node.js (v12) AWS Lambda that needs to pull data from my Firebase realtime database and process each record into a Redis cache if it doesn't exist already. function 啟動但從未完成,相反我收到來自 AWS Task timed out after 180.10 seconds
。
我嘗試過的事情:
exports.handler = async function(event)
與exports.handler = function(event, context, callback)
;context.callbackWaitsForEmptyEventLoop = false
而不是;.then()
拼接在一起;firebase-admin
與https
模塊與 Firebase REST ZDB97477ACE41 結合使用settimeout
稍后觸發回調而不是不使用;GOOGLE_APPLICATION_CREDENTIALS
環境變量設置為我的服務帳戶憑據,而不是直接在代碼中引用文件;根據上述嘗試,我得到的回應:
Task timed out after 180.10 seconds
;.then
拼接方式): Function completed successfully
(但實際沒有處理數據);ETIMEDOUT
或ECONNREFUSED
; 下面是我的目標,但仍然沒有運氣。 我已經刪除了緩存代碼,因為我知道它可以正常工作。 你看到的settimeout
是我到達這里之前的最后手段。
const admin = require("firebase-admin");
admin.initializeApp({
credential: admin.credential.applicationDefault(),
databaseURL: "https://{projectName}.firebaseio.com"
});
var result = [];
exports.handler = (event, context, callback) => {
context.callbackWaitsForEmptyEventLoop = false;
try {
admin.database().ref("data").orderByChild("timestamp").limitToLast(1).once("value", snapshot => {
if (snapshot.exists()) {
console.log('snapshot exists...');
let posts = snapshot.val();
result = Object.keys(posts);
}
setTimeout(() => {
admin.database().goOffline();
admin.app().delete();
callback(null, `Success! ${JSON.stringify(result)}`); // <-- NEVER RETURNS
}, 2000);
}, error => {
setTimeout(() => {
admin.database().goOffline();
admin.app().delete();
callback(error); // <-- NEVER RETURNS
}, 2000);
});
} catch (error) {
setTimeout(() => {
admin.database().goOffline();
admin.app().delete();
callback(error); // <-- NEVER RETURNS
}, 2000);
}
};
您似乎沒有在 function 的根級別上存儲或使用 setTimeout。 您應該存儲它,以便回調 function 可以繼續運行,因為它只存在於 scope 中。 這樣做還需要您綁定 object 以便在決定將其推入數組以進行多個回調時擁有自引用
var result = [];
var timeOut;
//...
timeOut = setTimeout(() => {
admin.database().goOffline();
admin.app().delete();
callback(error);
}.bind(this), 2000);
來源: MSDN Function.prototype.bind()
如果 Binding 不是解決方案並且您想要一種阻塞方法,您可能對延遲 function 感興趣,它的行為與 setTimeout 相同,但適用於 Promise
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
// Async function solution
await sleep(2000);
console.log('Two seconds later, showing sleep in a loop...');
// non-Async solution
sleep(2000)
.then(()=> {
admin.database().goOffline();
admin.app().delete();
callback(error);
})
.catch(e => console.log(e));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.