JSFiddle - React, Tailwind, and code Playground
by tomgrohl
HTML
<h2>Using .resolveWith and .rejectWith with single args</h2>
<div id="res"></div>
<br />
<h2>Using .resolveWith and .rejectWith with multiple args</h2>
<div id="res2"></div>
JavaScript
//Examples for
// - http://api.jquery.com/deferred.resolveWith/
// - http://api.jquery.com/deferred.rejectWith/
//Pass a single argument using deferred.resolveWith and deferred.rejectWith
function checkNumber( num ){
var dfd = new $.Deferred();
if( num > 10 )
{
//Add variable num to be passed to the
//.then and .done methods
dfd.resolveWith( $("#res"), [num] );
}
else
{
//Add variable num to be passed to the
//.then and .fail methods
dfd.rejectWith( $("#res"), [num] );
}
return dfd.promise();
}
checkNumber( 10 ).done(function( num ){
$(this).html("The number you entered: " + num + " was correct" );
}).fail( function( num ){
$(this).html("The number you entered: " + num + " was incorrect" );
});
//Pass multiple arguments using deferred.resolveWith and deferred.rejectWith
function checkNumbers( num1, num2 ){
var dfd = new $.Deferred();
if( num1 > num2 )
{
//Add variables num1 and num2 to be passed to
//the .then and .done methods
dfd.resolveWith( $("#res2"), [num1, num2]);
}
else
{
//Add variables num1 and num2 to be passed to
// the .then and .fail methods
dfd.rejectWith( $("#res2"), [num1, num2]);
}
return dfd.promise();
}
checkNumbers( 10, 20 ).done(function( num1, num2 ){
$(this).html( num1 + " is bigger than " + num2 );
}).fail( function( num1, num2){
$(this).html( num1 + " is smaller than " + num2 );
});