在云函数中返回承诺

时间:2018-06-26 18:50:45

标签: firebase promise google-cloud-functions

我正在尝试观察给定ref上的所有写入,并在给定的时间延迟(在本例中为5秒)后将其删除。当我部署以下云函数时,一旦我向引用添加新节点,但所有控制台日志均以正确顺序打印,该函数即会立即(在1秒内)返回。

exports.monitorActiveSignals = functions.database.ref('/names/{pushId}')
    .onCreate((snapshot, context) => {
         const key = snapshot.key;
         console.log(key);
         return wait(5000, snapshot).then((snap) => {
         console.log("timer done")
         snap.ref.remove();
         return;
   })
 })

const wait = (time, snap) => new Promise((resolve) => {
console.log(time)
console.log("timer started");
setTimeout(resolve(snap), time);
});

1 个答案:

答案 0 :(得分:4)

当您说setInterval(resolve(snap), time)时,您正在做的是在计时器开始前 调用resolve方法。然后,计时器触发后什么也没发生,因为resolve(snap)什么也不返回-没有要执行的函数。为了真正将resolve()的执行推迟到计时器触发之前,您为什么不尝试这样的操作呢?

exports.monitorActiveSignals = functions.database.ref('/names/{pushId}')
.onCreate((snapshot, context) => {
    const key = snapshot.key;
    console.log(key);
    return wait(5000, snapshot).then((snap) => {
        console.log("timer done")
        snapshot.ref.remove();
        return;
    })
})

const wait = (time, snap) => new Promise((resolve) => {
    console.log(time)
    console.log("timer started");
    setTimeout(resolve, time);
});