Firebase Promise链在catch块中终止

问题描述 投票:0回答:1

如果达到第一个catch块,我需要退出http函数。我正在跟随

    .then() <- start work related with database
            .then()
            .then()
            .catch(error => { <- Here I want to catch errors with firebase database and exit function.
              console.log(error)
              response.status(500).send(error)
            })
            .then() <- Here I want to send FCM message if there was no database errors
            .catch(error => {
              console.log(error)
              response.status(200).send("Success") <- Main work with database was finished. I still want to send http 200 and don't care about FCM errors.
           })
           .then(() => {
              response.status(200).send("Success")
           }) <-This catch block should be fired if there was an issue with FCM

问题是函数在第一个catch块之后继续运行。如何在第一个挡块中正确停止链条?谢谢

javascript firebase google-cloud-functions
1个回答
2
投票

使用传播值和顶级哨兵的组合,这样的事情应该有效:

let bail = false

doWork()
.then(result => {
    console.log(result)
    return true  // indicate success
})
.catch(error => {
    console.error(error)
    return false  // indicate error
})
.then(isPriorSuccessful => {
    if (!isPriorSuccessful) {
        bail = true
        return null
    }
    else {
        // do more stuff here, return a promise
        return doMoreWork()
    }
})
.catch(error => {
    console.error(error)
})
.then(() => {
    if (bail) {
        res.status(500).send("NOT OK")
        return
    }
    console.log("Just before the end")
    res.send("OK")
})
© www.soinside.com 2019 - 2024. All rights reserved.