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

时间:2018-07-31 14:07:29

标签: javascript 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);
        });
    });      
});

1 个答案:

答案 0 :(得分:1)

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

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

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