Below is a code snippet using async-waterfall method. How can i convert this using promise.
async.waterfall([
function(callback){
User.update({username: user.username}, {$set: update_list}, function(err, a_user) {
if (err) {
err = new Error();
err.code = 400;
err.message = "Unexpected error occurred."
callback(err)
}
if (!a_user) {
err = new Error();
err.code = 400;
err.message = "User not found."
callback(err)
}else{
callback(null, "updated", user_image);
}
})
}, function(message, user_image, callback){
if(user_image == undefined){
callback(null, "done")
}else{
Bean.update({username: user.username, status:"Active"}, {$set: {user_image:user_image}},{multi:true},function(err, beanUpdated){
if(err){
err = new Error();
err.code = 400;
err.message = "Unexpected error occurred."
callback(err)
}else{
callback(null, "done");
}
})
}
}
], function(err, result){
if(err){
return res.json({code:err.code, message:err.message})
}else{
return res.json({code:200, message:"Successfully updated profile."})
}
})
I usually use waterfall and series method of async module for synchronise my Node js code. Help me to switch from async to promise.
I will not rewrite your code for you but I will provide you enough information so that you could do it yourself in 3 different styles with examples demonstrating the concepts. Rewriting your code will give you a good opportunity to get familiar with promises.
Instead of functions taking callbacks and composing them with
async.waterfall
you can use functions returning promises and return those promises from thethen
callbacks, to use the resolved values of those promises in the nextthen
callback:Which in this simple example can be simplified to:
Or even this:
Or you can very easily compose them together with
async
/await
:Or even this in this particular case:
Here you handle errors with
try
/catch
:Code using
await
has to be inside of a function declared with theasync
keyword but you can use it anywhere by wrapping in something like this:The
(async () => { ... })()
expression itself returns a promise that is resolved to the return value of the async function or rejected with the exception thrown inside.Note that in the above examples each function can easily depend on the value of a resolved promise returned by the previous function, i.e. the exact use case of
async.waterfall
but we're not using any library for that, only native features of the language.The
await
syntax is available in Node v7.0+ with the harmony flag and v7.6+ without any flags. See:For more examples see this answer:
And for more background see the updates to this answer for more info: