javascript - Correct way to chain two promises when the second promise depends on the first? -


how make chain 2 jquery async calls using js promises while avoiding pyramid of doom? know can convert "jquery" promise real promise this:

promise.resolve($.getjson(url, params)); 

if want wait 1 promise, can this:

promise.resolve($.getjson(url1, params1)) .then(function(result){   // stuff }); 

if want wait 2 different ajax calls done, can this:

promise.all( [   promise.resolve($.getjson(url1, params1)),   promise.resolve($.getjson(url2, params2)) ]).then(function(results_array){   // stuff }); 

however, if want 1 call come after other one, doesn't work:

promise.resolve($.getjson(url1, params1)) .then(function(result){   //do stuff   return promise.resolve($.getjson(url2, params2)); }).then(function(result){   //result promise, not results second call getjson()...   //and doesn't wait second call finish.   //result.then() going bring me further pyramid of doom :( }); 

somehow, want call .then() on promise constructed in "do stuff" function. what's idiomatic way this?

return promise.resolve($.getjson(url2, params2)); 

what did create resolved promise (via promise.resolve) promise resolved value result of $.get(), promise. why "it doesn't wait second call finish" , "the result promise".

also, don't need wrap jquery ajax calls return promises. jquery's promises act (but not entirely) same native promises.

do instead:

$.getjson(url1, params1).then(function(result)){   return $.getjson(url2, params2); }).then(function(result)){   //result 2 }); 

additionally, you're using jquery. jquery ajax promises can done this:

$.getjson(url1, params1).then(function(result){   // stuff }); 

listening multiple promises can done way in jquery:

$.when($.getjson(...), $.getjson(...)).then(function(res1, res2){   // stuff }); 

Comments

Popular posts from this blog

python - No exponential form of the z-axis in matplotlib-3D-plots -

php - Best Light server (Linux + Web server + Database) for Raspberry Pi -

c# - "Newtonsoft.Json.JsonSerializationException unable to find constructor to use for types" error when deserializing class -