Difference of using async / await vs promises?

后端 未结 5 1585
Happy的楠姐
Happy的楠姐 2020-12-03 08:42

I am looking for a answer on what to use in my nodeJS app.

I have code which handles my generic dB access to mssql. This code is written using an async

5条回答
  •  春和景丽
    2020-12-03 09:01

    Its depending upon what approach you are good with, both promise and async/await are good, but if you want to write asynchronous code, using synchronous code structure you should use async/await approach.Like following example, a function return user with both Promise or async/await style. if we use Promise:

    function getFirstUser() {
        return getUsers().then(function(users) {
            return users[0].name;
        }).catch(function(err) {
            return {
              name: 'default user'
            };
        });
    }
    

    if we use aysnc/await

    async function getFirstUser() {
        try {
            let users = await getUsers();
            return users[0].name;
        } catch (err) {
            return {
                name: 'default user'
            };
        }
    }
    

    Here in promise approach we need a thenable structure to follow and in async/await approach we use 'await' to hold execution of asynchronous function.

    you can checkout this link for more clarity Visit https://medium.com/@bluepnume/learn-about-promises-before-you-start-using-async-await-eb148164a9c8

提交回复
热议问题