使用await异步获取数据而无需尝试捕获
问题描述:
为此,我尝试使用不带try-catch的await-async:
I am trying to use await-async without try-catch for this:
const getUsers = async (reject, time) => (
new Promise((resolve, reject) => {
setTimeout(() => {
if (reject) {
reject(....)
}
resolve(.....);
}, time);
})
);
module.exports = {
getUsers ,
};
使用try-catch块,它看起来像这样:
With try-catch block it looks like this:
const { getUsers } = require('./users');
const users = async () => {
try {
const value = await getUsers(1000, false);
.....
} catch (error) {
.....
}
}
users();
如何在不使用try-catch块的情况下编写相同的代码?
How can I write the same code without using the try-catch block?
答
使用then-catch函数,使过程更简单,我使用以下utils:
Using the promise functions then-catch to make the process simpler I use this utils :
// utils.js
const utils = promise => (
promise
.then(data => ({ data, error: null }))
.catch(error => ({ error, data: null }))
);
module.exports = utils;
然后
const { getUsers } = require('./api');
const utils = require('./utils');
const users = async () => {
const { error, data } = await utils(getUsers(2000, false));
if (!error) {
console.info(data);
return;
}
console.error(error);
}
users();
在不使用try-catch块的情况下,我得到了相同的输出,这样可以更好地理解代码.
Without using the try-catch block I got the same output, this way makes it better to understand the code.