javascript - Promise 不可迭代?函数错误

标签 javascript firebase firebase-realtime-database google-cloud-functions

我正在设置一个新的 Firebase Cloud Functions,以便在 Android 上与我的应用配合使用。我想做的就是当新记录写入数据库时​​向某些 token_ids 发送通知。但在我的 Javascript 代码中,我收到错误:

< Promise > is not iterable

在以下行中:

const results = await Promise.all(getDeviceTokensPromise);

该函数被触发,因此它可以正确检测数据库上的新写入/记录。但它不会发送任何通知。

希望有人能对此有所启发。提前致谢。

在我的数据库中, token 列表的索引如下:

/tokens
   /Vilanova
      /-LoReasGHj88MhbEj2Fn
        token:"xxxxxxxx"

      /-LoRf1fAA2ZhIu6JMLW7
        token:"xxxxxxxx"

这是函数代码:

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

//Evento Trigger On Write para nuevas alertas
exports.sendUsuariosNotification = functions.database.ref('/alertas/Vilanova/{alertaid}')
    .onWrite(async (snapshot, context) => {

// Referencia a lista de tokens en Vilanova
    const getDeviceTokensPromise = admin.database().ref(`/tokens/Vilanova/{tokenid}`).once('value');

// Snapshop para los tokens
    let tokensSnapshot;

    // Array para los tokens
    let tokens;

    const results = await Promise.all(getDeviceTokensPromise);
    tokensSnapshot = results;

// Si no se encuentran tokens, mostramos en log
    if (!tokensSnapshot.hasChildren()) {
        return console.log('No hay tokens disponibles para enviar notificaciones');
    }


console.log('Hay', tokensSnapshot.numChildren(), 'tokens para mandar notificaciones.');

//Información de la notificación
                const payload = {
                        "data": {
                                "title": "Nueva alerta",
                                "body": "",
                                "icon": "ic_launcher",
                                "sound": "default",
                            }
        }

// Listando los tokens en array
    tokens = Object.keys(tokensSnapshot.val());

    // Envio de notificaciones a todos los tokens
    const response = await admin.messaging().sendToDevice(tokens, payload);

    // Variable para comprobar si ha ocurrido un error con algún token
const tokensToRemove = [];

response.results.forEach((result, index) => {
    const error = result.error;
        if (error) {
            console.error('fallo al enviar notificacion a :', tokens[index], error);

            // Limpiamos los tokens no registrados o invalidos.
            if (error.code === 'messaging/invalid-registration-token' ||
                    error.code === 'messaging/registration-token-not-registered') {

                    tokensToRemove.push(tokensSnapshot.ref.child(tokens[index]).remove());
            }
        }
  });

  return Promise.all(tokensToRemove);

});

最佳答案

听起来 getDeviceTokensPromise 是一个 promise ,而不是一个数组。 Promise.all 期望一个 Promise 数组作为其参数(好吧,不一定是数组,而是可迭代的)。我怀疑你只是想要:

const results = await getDeviceTokensPromise;

...getDeviceTokensPromise 的实现值是一个数组。

关于javascript - Promise 不可迭代?函数错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57893093/

相关文章:

javascript - 满足所有条件后隐藏工具提示弹出窗口

javascript - puppeteer 师 - 错误 : Evaluation failed: ReferenceError: TABLE_ROW_SELECTOR is not defined

firebase - Flutter:Firebase 实时数据库 orderByChild 对查询结果没有影响

java - Firebase,在推送之前检查数据是否已经存在

swift - 如何检索 firebase 数据库值来计算平均值

javascript - 免费的 Javascript+Jquery IDE 吗?诸如智能感知等功能

android - Firebase 推送通知(android+node.js)

javascript - 如何从 map 对象返回一个字符串并发送到 firebase?

javascript - firebase.database() 不是函数 - 新的 Firebase 项目

javascript - react : Do children always rerender when the parent component rerenders?