What is await-to-js?
The await-to-js npm package is a utility that simplifies error handling in asynchronous JavaScript code. It allows developers to handle errors in a more readable and concise manner by using a tuple pattern with async/await syntax.
What are await-to-js's main functionalities?
Error Handling with Async/Await
This feature allows you to handle errors in asynchronous functions without using try/catch blocks. The `to` function returns a tuple where the first element is the error (if any) and the second element is the resolved value.
const to = require('await-to-js').default;
async function fetchData() {
const [err, data] = await to(fetch('https://api.example.com/data'));
if (err) {
console.error('Error fetching data:', err);
return;
}
console.log('Data:', data);
}
fetchData();
Custom Error Handling
This feature allows you to implement custom error handling logic by checking the error returned in the tuple and passing it to a custom error handler function.
const to = require('await-to-js').default;
async function fetchData() {
const [err, data] = await to(fetch('https://api.example.com/data'));
if (err) {
handleCustomError(err);
return;
}
console.log('Data:', data);
}
function handleCustomError(err) {
// Custom error handling logic
console.error('Custom Error Handler:', err);
}
fetchData();
Other packages similar to await-to-js
async-await-error-handling
The async-await-error-handling package provides a similar utility for handling errors in async/await code. It offers a `handle` function that returns a tuple with the error and result, similar to await-to-js. However, it may have a different API and additional features.
await-to
The await-to package is another alternative that provides a `to` function for handling errors in async/await code. It is very similar to await-to-js in terms of functionality and usage, making it a direct competitor.
await-to-js
Async await wrapper for easy error handling
Pre-requisites
You need to use Node 7.6 (or later) or an ES7 transpiler in order to use async/await functionality.
You can use babel or typescript for that.
Install
npm i await-to-js --save
Usage
import to from 'await-to-js';
async function asyncTaskWithCb(cb) {
let err, user, savedTask, notification;
[ err, user ] = await to(UserModel.findById(1));
if(!user) return cb('No user found');
[ err, savedTask ] = await to(TaskModel({userId: user.id, name: 'Demo Task'}));
if(err) return cb('Error occurred while saving task');
if(user.notificationsEnabled) {
[ err ] = await to(NotificationService.sendNotification(user.id, 'Task Created'));
if(err) return cb('Error while sending notification');
}
if(savedTask.assignedUser.id !== user.id) {
[ err, notification ] = await to(NotificationService.sendNotification(savedTask.assignedUser.id, 'Task was created for you'));
if(err) return cb('Error while sending notification');
}
cb(null, savedTask);
}
async function asyncFunctionWithThrow() {
const [err, user] = await to(UserModel.findById(1));
if (!user) throw new Error('User not found');
}
TypeScript usage
interface ServerResponse {
test: number;
}
const p = Promise.resolve({test: 123});
const [err, data] = await to<ServerResponse>(p);
console.log(data.test);
License
MIT © Dima Grossman && Tomer Barnea