Home>

The following source code is the breakthrough javascript page 99.
Each time you click on a document element, a console is displayed, but from the second time on, it delays processing for one second.

// jquery 3.3.1
var prevState = new $.Deferred (). resolve (). promise ();
function asyncFuncDef () {
    var deferred = new $.Deferred ();
    setTimeout (function () {
        deferred.resolve ("done");
    }, 1000);
    return deferred.promise ();
}
$(document) .on ("click", function () {
    prevState = prevState.then (function () {
        console.log ("done");
        return asyncFuncDef ();
    });
});


I'm wondering here: . promise () is. What does this have promise () for?
It works even ifvar prevState = new $.Deferred (). Resolve ()on the first line, but what effect is obtained by placing promise () at the end of the method chain Is it?

In the first place, why is processing completed in the first line of the source Have you resolved what you resolved ?

  • Answer # 1

    $. Deferred (). resolve ()only returns a Deferred object, butnew $.Deferred (). resolve (). promise ()Will return a promise object.

    I think this source is a sample that implements lazy execution with promise objects, so it will have the same types of objects to save as state.

    The Deferred object behaves the same as the promise object, so it can be used as is, but after the first click, the prevState becomes a promise object.

  • Answer # 2

    The jQuery manual says "chitin".

      

    This object (Note: The object returned by.promise ()) provides a subset of the methods of the Deferred object (omitted) to prevent users from changing the state of the Deferred. (jQuery Types More)