【问题标题】:Nodejs: Recall function in catch block returns undefined in a try-catchNodejs:catch块中的召回函数在try-catch中返回未定义
【发布时间】:2020-05-22 03:49:08
【问题描述】:

我在一个有 try-catch 的类中有一个异步函数。当尝试遇到错误时,我想召回函数重新尝试。

我当前的实现成功地调用了 catch 块中的函数,但是如果连续尝试成功,则返回的结果始终是 undefined

代码:

class Extractor {

    constructor(item) {
        this.item = item
    }

    async start() {

        try {
            let results = await someApiCallPromise()
            this.item.moreData = results
            return this.item //<== Upon sequential recall from catch, it always return undefined

        } catch (err) {
            if (err == "someError") {
                await this.start() // <== this.start() recalls successfully
            } else {
                //Other error handling method
            }
        } 
    }
}

//Usage
let item = {
    param1: '1',
    param2: '2'
}

let extractor = new Extractor(item)
extractor.start()
.then(item => {
    console.log(item) // <== Always return undefined if recalled from catch block
}) 

如果 this.item 从 catch 块中的召回成功,我该如何返回?

【问题讨论】:

    标签: javascript node.js


    【解决方案1】:

    您必须在catch 中进行return 递归调用: return this.start() 由于您是returning 一个承诺(调用异步函数),因此不需要await

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-15
      • 1970-01-01
      • 2012-05-18
      • 2019-08-31
      • 2016-05-06
      • 1970-01-01
      • 2011-11-04
      • 2021-12-25
      相关资源
      最近更新 更多