Nested Async await inside timer - not returning the desired value(在计时器内嵌套异步等待-未返回所需值)
本文介绍了在计时器内嵌套异步等待-未返回所需值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我必须使用Mocha和Chai测试测试端点的响应。下面是相同的代码:
async function getData (userId) {
let response;
let interval = setInterval(async () => {
response = await superagent.get("localhost:3000/user/details/").query({'user': userId}).type('application/json');
if (response.body["status"] == 'DONE') {
clearInterval(interval);
response = await superagent.get("localhost:3000/user/details/get").type('application/json');
}
}, 10000);
return response;
}
测试代码:
it('User Get Data', async function () {
return getData(userId,).then(function (res) {
expect(res).to.exist;
expect(res.status).to.equal(200);
expect(res.body).to.contain('operation');
expect(res.body["userDetails"]).to.exist;
});
我总是得到NULL响应,并且我的测试失败。请告诉我这个代码哪里出错了。
推荐答案
经过编辑以消除While循环:
您可以使用async/await重写getData,并将interval包装在承诺中。一旦第一个响应正常,请清除间隔,解析承诺,然后执行第二个呼叫。
在您的单元测试中,只需等待此函数,然后验证响应详细信息。请注意,您可能希望增加测试的默认mocha-timeout,因为这可能需要一段时间。类似于:
async function getData(userId) {
const firstResponsePromise = new Promise(resolve => {
const interval = setInterval(async() => {
const response = await superagent.get('localhost:3000/user/details/').query({
'user': userId
}).type('application/json');
if (response.body['status'] == 'DONE') {
clearInterval(interval);
resolve();
}
}, 10000)
});
await firstResponsePromise;
return superagent.get('localhost:3000/user/details/get').type('application/json');
}
// unit test
it('User Get Data', async function () {
const res = await getData(userId);
expect(res).to.exist;
expect(res.status).to.equal(200);
expect(res.body).to.contain('operation');
expect(res.body["userDetails"]).to.exist;
});
这篇关于在计时器内嵌套异步等待-未返回所需值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
编程基础网
本文标题为:在计时器内嵌套异步等待-未返回所需值
基础教程推荐
猜你喜欢
- 即使每次插入第一个输入的值不同,第二个输入仍显示相同的输入值 2022-01-01
- 使用 jQuery 在悬停时交换 DIV 类 2022-01-01
- 从快速中间件中排除路由 2022-01-01
- HTML5 画布调整为父级 2022-01-01
- CORS:当凭据标志为真时,无法在 Access-Control-Allow-Origin 中使用通配符 2022-01-01
- 逻辑运算符 ||在 javascript 中,0 代表 Boolean false? 2022-01-01
- 带角度的选项卡:仅使用 $http 在单击时加载选项卡 2022-01-01
- 当木偶师打开Chrome时,不能使用Chrome扩展 2022-01-01
- 在 Javascript 中使用 Fetch API 上传文件并显示进度 2022-01-01
- 最佳动态 JavaScript/JQuery 网格 2022-01-01
