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