rancor1223 rancor1223 - 1 month ago 6
Javascript Question

Trouble forming a promise chain

I have a function that has to connect to DB to get a upload token, then upload a file, then close the stream and log the file in DB. I'm having trouble chaining all this together.

var saveNewRequest = function (image_arr) {
return $.ajax({
url: 'http://' + AppVar.ServerUrlWithPort + '/restapi/MtReqNewRequest_SaveData',
type: 'POST',
data: JSON.stringify({
'SessionId': AppVar.SessionId,
'Name': $('#MtReqNewRequest_name').val(),
'Desc': $('#MtReqNewRequest_desc').val(),
'Obj': $('#MtReqNewRequest_obj').val(),
'Priority': $('#MtReqNewRequest_priority2').val(),
'Status': $('#MtReqNewRequest_status2').val(),
'Type': $('#MtReqNewRequest_type2').val()
}),
dataType: 'json',
contentType: "application/json",
timeout: 10000
}).done(function (response) {
if (response.ResultCode === '0') {
if (image_arr.length != 0) {
//this is recursively called upload function which returns jQuery promise (this works as intended)
// the promise resolves with RequestId which I need later on
return uploadImages(image_arr, image_arr.length, 0, response.RequestId)
} else {
//I would like this to return just this RequestId
Promise.resolve(response.RequestId)
}
} else {
Promise.reject().promise();
}
}).fail(function (x, t, m) {
if (t === "timeout") {
reject("Timeout: " + t);
} else {
reject($.i18n('Error-RetrivingDataProblem'));
}
})
}


And I call this in an event:

MtReq.saveNewRequest(image_arr).then(function (output) {
AppVar.nav.popPage().then(function () {
Utility.hideModalWithProgressBar();
if (!isNaN(output)) {
setTimeout(500, AppVar.nav.pushPage("MtReqRequestPage.html", { animation: "slide", id: output }));
}
})
}).catch(function (e) {
Utility.hideModalWithProgressBar();
ons.notification.alert(e);
})


I need to pass the RequestID to the
AppVar.nav.pushPage
, to open the page I just created. However, I'm getting whole response of the very first Ajax request in
saveNewRequest
.

This is Cordova app, using OnsenUI framework (but that's not relevant to the problem). Also, I'm using latest BluebirdJs as Promise polyfill (which to my knowledge should make JS and jQuery promises compatible).

Thanks for any help!

Answer

Substitute .then() for .done(); .done() returns same jQuery promise object returned by $.ajax(). return the Promise or other value from .then().

var saveNewRequest = function (image_arr) {
    return $.ajax({
        url: 'http://' + AppVar.ServerUrlWithPort + '/restapi/MtReqNewRequest_SaveData',
        type: 'POST',
        data: JSON.stringify({
            'SessionId': AppVar.SessionId,
            'Name': $('#MtReqNewRequest_name').val(),
            'Desc': $('#MtReqNewRequest_desc').val(),
            'Obj': $('#MtReqNewRequest_obj').val(),
            'Priority': $('#MtReqNewRequest_priority2').val(),
            'Status': $('#MtReqNewRequest_status2').val(),
            'Type': $('#MtReqNewRequest_type2').val()
        }),
        dataType: 'json',
        contentType: "application/json",
        timeout: 10000
    }).then(function (response) {
        if (response.ResultCode === '0') {
            if (image_arr.length != 0) {
                //this is recursively called upload function which returns jQuery promise (this works as intended)
                // the promise resolves with RequestId which I need later on
                return uploadImages(image_arr, image_arr.length, 0, response.RequestId)
            } else {
                //I would like this to return just this RequestId
                // added `return`
                return Promise.resolve(response.RequestId)
            }
        } else {
            // note `return`, removed `.promise()`
            return Promise.reject()        
        }
    }).fail(function (x, t, m) {
        if (t === "timeout") {
            // included `Promise`, chain `.reject()`
            // note, `return`
            return Promise.reject("Timeout: " + t);
        } else {
            // note `Promise.reject()`, added `return`
            return Promise.reject($.i18n('Error-RetrivingDataProblem'));
        }
    })
}