gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 01:24:20 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com