Bootcamp
Search…
4.1.3: Async/Await With Sequelize

Introduction

Async/await is a powerful tool to simplify our code, especially when performing DB queries with Sequelize. The following code builds on the migration and model setup from Module 4.1.2: Sequelize One-to-Many Relationships.

The following examples demonstrate how to use async/await with Sequelize. Note that the query code has to:
  1. 1.
    Be inside a function we declare as async
  2. 2.
    Be surrounded inside the async function with a try/catch block.

Get Category's Items

get-categorys-items.mjs

import db from './models/index.mjs';
​
const getCategorysItems = async () => {
try {
const category = await db.Category.findOne({
where: {
name: [process.argv[2]],
},
});
const categoryItems = await category.getItems();
console.log(categoryItems.map((categoryItem) => categoryItem.name));
} catch (error) {
console.log(error);
}
};
​
getCategorysItems();

Sample Command

node get-categorys-items.mjs fruit

Sample Output

[ 'some item', 'other item', 'iitemmm', 'banana' ]

Get Item's Category

get-items-category.mjs

import db from './models/index.mjs';
​
const getItemsCategory = async () => {
try {
const item = await db.Item.findOne({
where: {
name: [process.argv[2]],
},
});
const itemCategory = await item.getCategory();
console.log(itemCategory.name);
} catch (error) {
console.log(error);
}
};
​
getItemsCategory();

Sample Command

node index.mjs banana

Sample Output

fruit
Copy link
On this page
Introduction
Query Related Tables Using Async/Await
Get Category's Items
Get Item's Category