javascript - 如何从异步类函数 JavaScript 返回 Promise

标签 javascript asynchronous async-await promise es6-promise

我正在尝试对我使用 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);
        });
    });      
});

最佳答案

将函数的内部主体更改为:

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

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

关于javascript - 如何从异步类函数 JavaScript 返回 Promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51615341/

相关文章:

javascript - 无法让 onclick 事件的函数在 Javascript 中工作

c++ - 服务器关闭永远不会完成

node.js - NodeJS 异步/等待和函数调用

reactjs - 如何将 node_modules/regenerator-runtime/runtime.js 添加到 webpack 中捆绑

javascript - 使用 chrome.tabs.executeScript 执行异步函数

c# - 任务异常管理c#

javascript - 将窗口对象存储在本地存储中

javascript - 在javascript中添加浮点值

javascript - 使用elasticsearch按字母顺序排序

iphone - UITableview dequeueReusableCellWithIdentifier 重复行