scopsy / await-to-js

Async await wrapper for easy error handling without try-catch
http://blog.grossman.io/how-to-write-async-await-without-try-catch-blocks-in-javascript/
MIT License
3.27k stars 153 forks source link

Do we even need reject? #24

Closed Fenny closed 5 years ago

Fenny commented 5 years ago

Do we need the reject callback inside a promise? The below code seems to be working out for me, it catches any error and instead of rejecting it returns null in the resolve function. Is this bad code, if so why?

function fecthDB() {
    return new Promise((resolve, reject) => {
        try {
            db.query('SELECT * FROM users' (err, result) => {
                if (err || !results) {
                    return resolve(null)
                }
                resolve(result)
            })
        } catch (e) {
            resolve(null)
        }
    })
}

function async getUsers() {
    var users = await fecthDB()
    if (!users) { // error handling
        return console.log('error')
    }
    console.log(users) // got users
}
scopsy commented 5 years ago

@Fenny Sometimes you want to react on some errors based on their type. For example, the DB returned some validation error and you want to handle it differently than there was no result matching your request. Errors are powerful tool in software development and we should not ignore it altogether because it may put our software in a broken state without us knowing about it :)