The async/await instruction

The async and await are two instructions that come to save our life from the Promise chaos. This will allows us to write asynchronous code using asynchronous syntax. Let's organize our code to see how this works!

First, we will need to create a new function for the update process, as follows:

...
const Team = require('../models/team')

const updateTeam = async (id, teamBody) => {
try {
let team = await Team.findById(id)

if (team == null) throw new Error("Team not found")

team.code = teamBody.code || team.code
team.name = teamBody.name || team.name
team.ranking = teamBody.ranking || team.ranking
team.captain = teamBody.captain || team.captain
team.trainer = teamBody.trainer || team.trainer
team.confederation = teamBody.confederation || team.confederation

team = await team.save()
return team

} catch (err) {
throw err
}
}

api
.route('/teams')
...

The first thing to note in the preceding code is the async keyword. This keyword will wrap the returning result into a Promise and will allow us to use the await keyword. You cannot use await keyword in a non-async function. The await keyword will wait for the asynchronous call Team.findById(id) to end and will return the result. The same happens when we call the team.save() method.

Using async-await helps us avoid the Promise chaos. It provides us with an execution flow that might look like an asynchronous execution.

Once we have defined the updateTeam async function, we need to modify our PUT endpoint to call this new function:

...
})
.put((req, res, next) => {
updateTeam(req.params.id, req.body)
.then(team => res.json(team))
.catch(err => next(err))

})
.delete((req, res) => {
// TODO
})
...

We said that async will wrap the result into a Promise, so to use the result, we will need to use the then and catch methods to process the returning Promise.

That's it! Now we are ready to learn how to delete an existing object.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset