javascript - Aren't promises just callbacks? -


i've been developing javascript few years , don't understand fuss promises @ all.

it seems change:

api(function(result){     api2(function(result2){         api3(function(result3){              // work         });     }); }); 

which use library async anyway, like:

api().then(function(result){      api2().then(function(result2){           api3().then(function(result3){                // work           });      }); }); 

which more code , less readable. didn't gain here, it's not magically 'flat' either. not mention having convert things promises.

so, what's big fuss promises here?

promises not callbacks. promise represents future result of asynchronous operation. of course, writing them way do, little benefit. if write them way meant used, can write asynchronous code in way resembles synchronous code , more easy follow:

api().then(function(result){     return api2(); }).then(function(result2){     return api3(); }).then(function(result3){      // work }); 

certainly, not less code, more readable.

but not end. let's discover true benefits: if wanted check error in of steps? hell callbacks, promises, piece of cake:

api().then(function(result){     return api2(); }).then(function(result2){     return api3(); }).then(function(result3){      // work }).catch(function(error) {      //handle error may occur before point }); 

pretty same try { ... } catch block.

even better:

api().then(function(result){     return api2(); }).then(function(result2){     return api3(); }).then(function(result3){      // work }).catch(function(error) {      //handle error may occur before point }).then(function() {      //do whether there error or not      //like hiding spinner if performing ajax request. }); 

and better: if 3 calls api, api2, api3 run simultaneously (e.g. if ajax calls) needed wait three? without promises, should have create sort of counter. promises, using es6 notation, piece of cake , pretty neat:

promise.all([api(), api2(), api3()]).then(function(result) {     //do work. result array contains values of 3 fulfilled promises. }).catch(function(error) {     //handle error. @ least 1 of promises rejected. }); 

hope see promises in new light now.


Comments

Popular posts from this blog

ZeroMQ on Windows, with Qt Creator -

unity3d - Unity SceneManager.LoadScene quits application -

python - Error while using APScheduler: 'NoneType' object has no attribute 'now' -