【问题标题】:How to return Promise from an async class function JavaScript如何从异步类函数 JavaScript 返回 Promise
【发布时间】:2021-02-13 21:34:50
【问题描述】:

我正在尝试对使用 Promise 重写的代码进行单元测试。 FileFactory 类具有以下异步功能:

    async getFileHandler(filePath) {
    var self = this;
    for(const item of self.privateFileHandlers) {
        await item.canHandle(filePath)
        .then(function(response) {
            console.log("Response:",JSON.stringify(response));  //line A
            return response;
        }, function(error) {
            return error;
            //ignore since most handlers won't be able to handle.
            //also, the callback after the loop will inform that no filehandler was found.                
        })
        .catch(function(err){
            //console.log('Catching: ',JSON.stringify(err));
            return err;
            //ignore since most handlers won't be able to handle.
            //also, the callback after the loop will inform that no filehandler was found.
        });
    }
}

我在 A 行登录的响应包含我所期望的内容。

但是,在我的单元测试中,我没有得到响应对象。

        it('should return correct FileHandler child instance', function(){  
        var ff = new FileFactory();
        ff.getFileHandler("./tests/H1_20180528.csv").then(function(value) {console.log("Success",JSON.stringify(value));}).catch(function(err) {console.log("Fail",JSON.stringify(err));});
        //ff.getFileHandler("./tests/H1_20180528.csv").then(value => console.log("Success",JSON.stringify(value)));
        //console.log(JSON.stringify(fh));
    });

我在这里缺少什么? 谢谢。

这行得通:

async getFileHandler(filePath) {
    var self = this;
    for(const item of self.privateFileHandlers) {
        try {
            let response = await item.canHandle(filePath);
            if(response.status === "success")
                return response;
        } catch(e) {
            //ignore so it does not return on failed canHandle calls.
        }
    }
    throw 'No supporting file handler available.';
}

//更新的单元测试

describe('Select handler', function () {
    it('should fail and return no file handler.', function () {
        var ff = new FileFactory();
        ff.getFileHandler("./tests/H1_20180528_fail2.csv")
        .then(function (value) {
            chai.assert(value.status === null);
        })
        .catch(function (err) {
            chai.assert(err !== null);
        });
    });

    it('should return correct FileHandler child instance', function () {
        var ff = new FileFactory();
        ff.getFileHandler("./tests/H1_20180528.csv")
        .then(function (value) {
            chai.assert(value.status === 'success');
        })
        .catch(function (err) {
            chai.assert(err === null);
        });
    });      
});

【问题讨论】:

  • asyncawait 的全部意义在于它们允许您避免明确的 Promise 争吵。 await fn() 之后的代码被隐式视为在 .then() 回调中。
  • value 在你的测试中你期待什么?你的 getFileHandler 没有 return 任何东西。
  • 为什么要复制错误处理代码?
  • 我来自 OOP,这是我第一次处理 JS 中的 Promise。承诺的结构提供了拒绝和捕获,所以我都填写了。事实证明这里不需要。

标签: javascript asynchronous async-await promise es6-promise


【解决方案1】:

将你的函数的内部体改成这样:

try {
   let response = await item.canHandle(filePath);
   console.log("Response:", JSON.stringify(response)); // line A
   return response;
} catch (err) {
   return err;
}

如果您在async 函数中使用await 函数,则不必使用thencatch

【讨论】:

  • 在循环中return 是没有意义的,不是吗?
  • 有道理。从循环返回只是跳出循环。如果他想遍历他的文件处理程序,默默地忽略所有出错的处理程序,并返回第一个成功的处理程序怎么办?
  • 那是我的意图。
  • @kfedorov91 是的,这可能是 OP 的意图,但不幸的是,问题中没有说明。
猜你喜欢
  • 2023-03-08
  • 2019-10-23
  • 2020-07-09
  • 2017-10-16
  • 1970-01-01
  • 2018-04-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多