Search code examples
jqueryjquery-deferredspservices

jQuery deferred/promise with SPService library


I'm trying to get my promise item from SPService SPGetListItemsJson. The issue is that when SPGetListItemsJson is invoked and when requestPromise is done and the deferred is resolve, I would expect the data to pass into my anonymously function in populateDropDownControlWithList but its undefined.

   function populateDropDownControlWithList(option, control, addSelectValue)
    {
        if (typeof (addSelectValue) === 'undefined')
        {
            addSelectValue = false;
        }

        var selectedIndex = control.val() ? control.val() : -1;    
        if (addSelectValue)
        {
            control.append('<option value=-1>Select an Option</option>');
        }

        var request = SPGetListItemsJson(option);
        request.done(function (data) // Expect the json object here but it is undefined
        {
            $.each(data, function () 
            {
                controlappend('<option value=' + this.Id + '>' + this.Title + '</option>');
            });
        });
    }

    function SPGetListItemsJson(option)
    {
        var deferred = $.Deferred();
        var requestsPromise = $().SPServices.SPGetListItemsJson({
            listName: option.Name,
            CAMLQuery: option.Query,
            CAMLViewFields: option.View,
            mappingOverrides: option.Mapping,
            debug: option.Debug,
            async: option.async
        });

        requestsPromise.done(function ()
        {
            deferred.resolveWith(this.data); // Verified this.data is populated with the correct result
        });

        return deferred.promise();
    }

Any help would be greatly appreciated!


Solution

  • By making the following changes I was able to get it to work now. I'm posting it incase someone finds this useful.

    request.done(function ()
    {
        $.each(this, function () 
        {
            control.append('<option value=' + this.ID + '>' + this.Title + '</option>');
        });
    });
    

    Thanks!