Showing posts with label Promises. Show all posts
Showing posts with label Promises. Show all posts

Friday, February 26, 2016

How to use Deferreds and Promises in ajax call

//Ajax function

getPromise: function (serviceUrl, folderId, featureId, loginId, sessionId) {
        var deferred = $.Deferred();

        $.ajax({
            type: "POST",
            url: serviceUrl + "/test.asmx/getFolderFeaturePrivilegeList",
            contentType: "application/json; charset=utf-8",
            data: '{"folderId":"' + folderId + '","featureId":"' + featureId + '","loginId":"' + loginId + '","sessionId":"' + sessionId + '"}',
            dataType: "json",
            success: function (data) {
                deferred.resolve(data.d);
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert("Error has occured");
            }
        });

        //setTimeout(function () {
        //    deferred.resolve("hurray");
        //}, 1000);

        return deferred.promise();
    }

//calling function


download: function (serviceUrl, folderId, featureId, loginId, sessionId) {
        alert('download');
        $.when(ecabSettings.getPromise(serviceUrl, folderId, featureId, loginId, sessionId)).done(function (value) {
            alert('hi');
            console.log(value);
        });  
    },