How to allow / reject a jQuery Deferred object with the same "allowed / rejected" state of another pending?

I am writing several functions that effectively defer objects that depend on different combinations of other deferred objects.

function takesOneSecond() { return $.Deferred(function(deferred) { // Does something... }).promise(); } function takesOneMinute() { return $.Deferred(function(deferred) { // Does something... }).promise(); } function takesThreeMinutes() { return $.Deferred(function(deferred) { // Does something... }).promise(); } function mySwitchingFunction() { return $.Deferred(function(deferred) { // Does something here.. // Effectively chooses one of several other functions to call. if(/* choose 1 second */) { // We tie ourselves to the '1 second' function. // Call that function. takesOneSecond().done(function() { deferred.resolve(); // If that done, I'm done too. }).fail(function() { deferred.reject(); // If that failed, I've failed too. }); } else if(/* choose 1 minute */) { // Etc.. } else if(/* choose 3 minutes */) { // Etc.. } }).promise(); } 

I write this piece of code a lot, is there no other way to make a deferred mirror or cascade the same “allowed” or “rejected” state of another deferred?

 takesOneSecond().done(function() { deferred.resolve(); // If that done, I'm done too. }).fail(function() { deferred.reject(); // If that failed, I've failed too. }); 
+4
source share
2 answers

I think you don’t need to build a new promise at all. Just return the first promise.

 function mySecondFunction() { // Does something here.. // Effectively chooses one of several other functions to call. // In this case, assume I've just chosen the 'myFirstFunction' function. // Call that function and return its promise return myFirstFunction(); } 

If you want to emphasize the “at the same time” part, but maybe decide a different value, you can simply create a new one by linking with .then :

 function mySecondFunction() { return myFirstFunction().then(function(resultOfFirst) { // but ignore it and return differentResult; }); // errors will propagate automatically } 
+1
source

I think you may not understand promises. Using the .then promise method (pipe in jQuery <1.8), you can return a new promise and so on. This is how you create a promise chain.

Here is an example of what looks like what you are trying to do:

 function returnOne() { return $.Deferred(function( dfr ) { dfr.resolve( 1 ); }).promise(); } // Number will be the result of the original Deferred/Promise function addTwo( num ) { return $.Deferred(function( dfr ) { dfr.resolve( num + 2 ); }).promise(); } returnOne().then( addTwo ).then(function( result ) { // Will be 3 console.log( result ); }); 

Using this logic, you can filter the resolution or deviations of your promises, but you want to, including just re-resolving or rejecting with the same value, but maybe doing some intermediate work

+1
source

Source: https://habr.com/ru/post/1491899/


All Articles