问题
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 ,
};
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();
How can I write the same code without using the try-catch block?
回答1:
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;
And then
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();
Without using the try-catch block I got the same output, this way makes it better to understand the code.
回答2:
If you have a valid default for the error case you can use the catch
method on the getUsers
promise and then await
a promise whose error will be handled
const users = async () => {
const value = await getUsers(1000, false).catch(e => null);
}
While this approach should work it should be noted that this may mask the case when getUsers
returns null
vs when it raises an error, and you will still need to check for the null
or get a null access error. All in all I would stick with the try { .. } catch (e) { ... }
for most casses
回答3:
A package I found called await-to-js can also help it.
import to from 'await-to-js';
const [err, users] = await to(getUsers());
if(err) doSomething();
The idea is like Lyes CHIOUKH's method, just a wrapper. Copied the source code here.
/**
* @param { Promise } promise
* @param { Object= } errorExt - Additional Information you can pass to the err object
* @return { Promise }
*/
export function to<T, U = Error> (
promise: Promise<T>,
errorExt?: object
): Promise<[U | null, T | undefined]> {
return promise
.then<[null, T]>((data: T) => [null, data])
.catch<[U, undefined]>((err: U) => {
if (errorExt) {
Object.assign(err, errorExt);
}
return [err, undefined];
});
}
export default to;
回答4:
@saibbyweb
To save data into mongoose we can do this,
Util:
module.exports = promise => {
return promise.then(data => [null, data]).catch(error => [err]);
}
Object to save into mongoose
const Todo = require('../models/todo');
function todoObj(todoObject) {
return todo = new Todo({
task: todoObject.task,
label: todoObject.label,
progress: todoObject.progress,
isImportant: todoObject.isImportant,
priority: todoObject.priority
});
}
exports.todoObj = todoObj;
Import util
//Callback handler helper
const promiseHandler = require('../../utils/promiseHandler');
//Models
const Todo = require('../../models/todo');
let err = null;
let data = null;
app.route('/')
//Get all To-dos
.get(async (req, res, next) => {
[err, data] = await promiseHandler(Todo.find().exec());
if (err) return res.status(400).json(response(400, err, []));
return res.status(200).json(response(200, 'All todo', data));
})
//Create Todo
.post(async (req, res, next) => {
const { task } = req.body;
if (isDefVar(task)) {
const todo = todoObj(req.body);
[err, data] = await promiseHandler(todo.save());
if (err) return res.status(400).json(response(400, err, []));
return res.status(200).json(response(200, 'Todo saved', data));
}
})
module.exports = app;
But I would not recommend for large projects and if you have two asynchronous calls in the same function. It will so difficult to handle.
来源:https://stackoverflow.com/questions/50210289/get-data-using-await-async-without-try-catch