Alex Griffiths
Alex Griffiths

Reputation: 3

Node.js best way to handle promises

So I have code that looks like this in my controller.

const Users = require("../models/users");    

class UserController() {
    getUserById(req, res) {
        const id = req.params.id;
        const users = new Users();
        const userData = users.getUserById(uid).then(function(result) {
            //Do other logic here that depends on db result
            return res.status(200).json({status:"success", user: result});
        });
    }
}

My question is, what's the difference between that and the following, and which is the better practice?

const Users = require("../models/users");    

class UserController() {
    async getUserById(req, res) {
        const id = req.params.id;
        const users = new Users();
        const userData = await users.getUserById(uid);
        return res.status(200).json({status:"success",user:userData});
    }
}

Upvotes: 0

Views: 73

Answers (1)

Imran Rafiq Rather
Imran Rafiq Rather

Reputation: 8078

The second function call is using async-await feature of ES8, This makes our code appear as if it is synchronous and clean also, without doing .then() and callback within it. Both fetch() and async-await work on promise though.

Aync-Await is much more readable if I can put it this way. No call backs used here. It simply waits for the first API call to happen and only when the data arrives (or Promise is resolved) we fire another API call. For programmer itself life becomes little easy with Async-Await syntax.

For Error handling you will need try{} catch{} block in Aync-await but in case of fetch(), .catch() block handles API Errors for us.

Upvotes: 1

Related Questions