I have another callback/promise issues :-)
I'm trying to implement a series of function each of the function are waiting for a return value from the next one.
I have an ajax call that returns a json on success, in the success block i'm sending this json to an async function validation.
In validation()
I'm loading a script and for each object I sending it to
availability function, i want to wait for the availability to complete and to return value, each value that is return is being
pushed to an array that i want to send it in the end.
I'm having trouble with the callback implementations.
var validArr = [];
function checkStory(callback) {
$.ajax({
url: "",
type: "GET",
data: "",
async: true,
headers: {
Accept: "application/json"
},
success: function(data) {
if (data.isDoc == true) {
_checkDoc(callback);
} else {
if (data.responseObj) {
validation(data.responseObj);
} else {
callback(data.count);
}
}
},
error: function(err) {
console.log("No books");
}
});
}
function validation(responseObj) {
getScript('books.js',
function() {
$.each(responseObj, function(_index, _value) {
var res = aviliabilty(_value);
if (res) {
validArr.push(_index, true);
} else {
validArr.push(_index, false);
}
});
//return after all objects completed execution
return validArr;
}
);
}
function aviliabilty(entry) {
DM.ct.get(entry, function(response) {
if (response) {
for (var idx = 0, adLen = response.ds.length; idx < adLen; idx++) {
var bk = response.ds[idx];
for (var creaIdx = 0, crea = bk.creatives.length; creaIdx < crea; creaIdx++) {
var creative = bk.creatives[creaIdx];
if (creative.type == "line") {
for (var mfIdx = 0, mfLen = creative.Files.length; mfIdx < mfLen; mfIdx++) {
var mediaFile = creative.Files[mfIdx];
if (mediaFile.type == "horror") {
return true;
}
}
} else if (creative.type != "horror") {
return false;
}
}
}
}
});
}
// a function to get the script asynchronously
function getScript(url, success) {
var script = document.createElement('script');
script.src = url;
var head = document.getElementsByTagName('head')[0],
done = false;
// Attach handlers for all browsers
script.onload = script.onreadystatechange = function() {
if (!done && (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete')) {
done = true;
success();
script.onload = script.onreadystatechange = null;
head.removeChild(script);
}
};
head.appendChild(script);
}