gpt4 book ai didi

node.js - (..).then 不是函数,firebase 云函数

转载 作者:搜寻专家 更新时间:2023-11-01 00:05:27 24 4
gpt4 key购买 nike

我正在尝试异步运行一个函数。但它会抛出错误。下面是我的代码:

exports.listenForNotificationRequests = functions.database.ref('/notificationRequests/{pushId}')
.onWrite(event => {
const requestId = event.data.val();
var sentTo = requestId.sentTo;
var senderIds = sentTo.split(",");
// var senderTokens = "";

var payload = {
data: {
title: requestId.username,
message: requestId.message,
sentFrom: requestId.sentFrom
}
};

getSenderIds(senderIds).then(function(senderTokens){
console.log("SenderTokens", senderTokens);
admin.messaging().sendToDevice(senderTokens.split(","), payload)
.then(function(response) {
console.log("Successfully sent message:", response);
})
.catch(function(error) {
console.log("Error sending message:", error);
});

});

});

function getSenderIds(senderIds){
var senderTokens = "";
senderIds.forEach(function (snapshot){
var ref = admin.database().ref("users/"+snapshot+"/token");
console.log("refernce", snapshot);
ref.once("value", function(querySnapshot2) {
var snapVal = querySnapshot2.val();
console.log("Token", snapVal);
senderTokens = senderTokens+","+snapVal;
});
});
return senderTokens;
}

执行时抛出异常:

TypeError: getSenderIds(...).then is not a function
at exports.listenForNotificationRequests.functions.database.ref.onWrite.event (/user_code/index.js:20:39)
at /user_code/node_modules/firebase-functions/lib/cloud-functions.js:35:20
at process._tickDomainCallback (internal/process/next_tick.js:129:7)

我尝试了多种解决方案,但都没有用。这里有人可以指出我犯了什么错误吗?或者是否有任何其他解决方案?

最佳答案

要使用 then(),您的 getSenderIds() 应该返回一个 Promise,而此时它返回一个字符串。

ref.once() 确实返回一个 Promise。您可以做的是将 senderTokens 设为一个数组,并在每次迭代时将 ref.once() 推送到该数组。

因为 ref.once() 返回一个 Promise,这使得 senderTokens 成为一个包含每个查询结果的 Promises 数组。然后您可以返回 Promise.all(senderTokens) read more about Promise.all here .

然后在 then (function(senderTokens){}) 里面做 to String 处理 通过在 senderTokens 数组的每一项上调用 .val() 来阻止。

关于node.js - (..).then 不是函数,firebase 云函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43865478/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com