We have an application that is growing and our client side scripting needs to be refactored to be cleaner, leaner, and more maintainable. I'm attempting to take a small module a utilize Q library for promise chaining.
As you can see I need to pass some return values back from the initial function to the rest of the promise chain. Can someone please help me understand what I need to do to get the first function returning properly as a Promise? And then explain the chain?
Here is my starting point:
var promise = new Q.Promise(generateMoveRequest)
.then(function (id) {
var woNum = 12345;
return layoutInit(woNum, id, true);
}).then(function (result) {
if (result) {
return moveRequestInit(result, true);
} else {
throw new Error('Template not loaded');
}
}).catch(function (err) {
console.log(err);
});
Generate Move Request:
generateMoveRequest: function () {
$.ajax({
method: "GET",
url: window.contextPath + '/api/settings/getjson',
data: {name: "the_name"},
success: function (data) {
if (data.length) {
var id = $.parseJSON(data).Parent;
return id;
}
},
error: function (xhr, textStatus, errorThrown) {
console.log("xhr: ", xhr);
return null;
}
});
}
Layout Init:
layoutInit: function (num, id, appendLayout) {
$.ajax({
method: "GET",
url: window.contextPath + '/some/url',
data: {num: num, id: id},
success: function (data) {
return layoutInit.callback(data, appendLayout);
},
error: function (xhr, textStatus, errorThrown) {
console.log("xhr: ", xhr);
}
});
},
callback: function (data, appendLayout) {
if (data && data.toString().toLowerCase() !== "blank") {
if (appendLayout) {
$(data).insertBefore($("#detailsection"));
} else {
$("#detailsection").html(data);
}
} else {
$("#detailsection").html('');
}
},
The generateMoveRequest function will execute but the chain never proceeds any further. No .then() execution and layoutInit never gets called.
I'm using the Q Library but some of the examples seem to leave out how to start/create the promise or turn the initial function into a Promise.
Can someone explain what I have wrong here or provide me with a clean example?