1

I have been trying to understand the benefits of jQuery's Deferred functionality. If I understand correctly Deferred's doesn't offer an alternative to callbacks but rather offers better management of callbacks? If I am writing a method and I want to be sure that it has finished executing before running another task I would still need a callback to set the deferred.resolve? Here is a code example to illustrate what I think is correct:

This is the parent function. I want to ensure 'AddItemsToList' has completed before I select the default. (This isn't a real function, just an example).

function PopulateListAndSelectDefault(list,default)
{
   var resultObject = AddItemsToList($('#myList'), list);

   successObject.Success(function(){
      SelectItemInList($('#myList'), default);
   });
}

This would be the incorrect way to write the 'AddItemsToList' function:

function AddItemsToList (jquerySelectList,items)
{
   var result= $.Deferred();
   $.each(items, function (i, _property) 
   {
      if (CheckElementIsSelectList(_property.Value)) 
      {
          jQueryListItem.append($("<option></option>").attr("value", _property.value).text(_property.DisplayText)); //Add Item
      }
   }
   result.resolve;
   return result;      
}

Instead, the correct way, would be to continue to use a callback but this time only resolve the deferred object so that I can attach futher success/failure methods later down the line if I so wished?

Have I understood correctly? What would be the correct way to write the code above or have I completely misunderstood the fundamentals? Thanks in advance.

4

1 回答 1

1

这对于异步函数最有用。这是一个用于管理回调的实用程序类。

jQuery.Deferred() 是一个可链接的实用程序对象,可以将多个回调注册到回调队列中,调用回调队列,并中继任何同步或异步函数的成功或失败状态。

   

jQuery.Deferred() 提供了灵活的方式来提供多个回调,并且无论原始回调调度是否已经发生,都可以调用这些回调。

在异步函数中正确使用$.Deferred, 是在异步操作完成后返回 apromiseresolveDeferred 。

将任何值(可能是函数的结果)传递给 .resolve() 并且注册的回调将接收该值。

例子:

function getSomething() {
    var deferred = new $.Deferred;
    $.get('/get-something', function(data) {
        deferred.resolve(data);
    });
    return deferred.promise();
}

myAsynchronousFunction().done(function(data) {
    // ...
});

在这种情况下,这相当于:

function getSomething(callback) {
    $.get('/get-something', function(data) {
        callback(data);
    });
}

myAsynchronousFunction(function(data) {
    // ...
});
于 2011-09-07T11:21:46.977 回答