javascript - How to simplify deep nested promises -
i have come across situation need break @ every "else" clause in then(), , doesn't better nested callbacks, login process:
user.findone({ username: username }).exec() .then(user => { if (user) { return user.verifypassasync() .then(matched => { if (matched) { return user.getbriefprofile(username)) .then(emp => { if (emp) { return savetosession(emp); } else { //return }}) } else { //return ... }}) } else { // return false } }) is there way can simplify this?
not really, you're not (only) nesting promises here rather conditionals. if written async/await (es7), function like
var user = await user.findone({username}).exec(); if (user) { var matched = await user.verifypassasync(); if (matched) { var emp = await user.getbriefprofile(username); if (emp) { return savetosession(emp); } else { // return …; } } else { // return …; } } else { // return …; } as can see, nesting inherent program. it's bit simplified though (no nesting then calls), , can right promise.coroutine , es6 generators.
your best bet might throw error in each else, , linearise chain that, .catching in end. of course, if doing same thing in each else block, write
var user = await user.findone({username}).exec(); if (user) var matched = await user.verifypassasync(); if (matched) var emp = await user.getbriefprofile(username); if (emp) { return savetosession(emp); else // return …; which translates then callbacks:
user.findone({username: username}).exec() .then(user => user && user.verifypassasync() ).then(matched => matched && user.getbriefprofile(username); ).then(emp => emp ? savetosession(emp) : …; );
Comments
Post a Comment