Prerequisite: To follow along with this article, you need to know the basics of promises.
In Node.js, the typical way to achieve concurrency is by using one of the promise
methods — the most common being Promise.all()
.
Imagine you want to query a database with a list of IDs for a list of users and you want to act on the data returned (e.g. create a new user if the ID didn’t return a user).
One way to do this would be:
async function findOrCreateUser(id){
const user = await findUser(id)
if(!user){
return await createUser(id)
}
return user
}
async function run(idList){
let userList = []
for await (const id of idList){
const user = await findOrCreateUser(id)
userList.push(user)
}
}
#javascript #software-development #promises #programming #nodejs