[英]How to return Promise from an async class function JavaScript
I am trying to unit test a code I re-wrote using promises.我正在尝试对我使用 Promise 重新编写的代码进行单元测试。 The class FileFactory has the following async function: 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.
});
}
}
The response I am logging on line A contains what I would expect.我在 A 行上登录的响应包含我所期望的。
However, in my unit test, I don't get the response object.但是,在我的单元测试中,我没有得到响应对象。
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));
});
What am I missing here?我在这里缺少什么? Thank you.谢谢你。
This works:这有效:
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.';
}
//the updated unit test //更新的单元测试
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);
});
});
});
Change the inner body of your function to this:将函数的内部主体更改为:
try {
let response = await item.canHandle(filePath);
console.log("Response:", JSON.stringify(response)); // line A
return response;
} catch (err) {
return err;
}
If you're await
ing a function within an async
function you don't have to use then
or catch
.如果您正在await
async
函数中的函数,则不必使用then
或catch
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.