This is my first attempt to utilize asynchronous javascript. I've tried hooking up every incarnation of promises that I can find, but have not been able to write them successfully to get my string to return (i.e. $.Deferred, async/await, Promise, callbacks, relying on .done). async:false as an ajax variable works, but I'm trying to avoid settling for what I understand is bad practice. I would love to use async/await because it is so concise, but at this point I'm up for anything that works. I have a suspicion that I'm trying to utilize the $.ajax return in an incorrect manner.
Much appreciation for a working return of the string wholename (a randomized first and last name), examples of a few versions for my own education even more appreciated!
function Actor(gender, name) {
if (gender == "" || gender == undefined) {this.gender = "female";} else this.gender = gender;
if (name == "" || name == undefined) {this.name = makeName(this.gender);} else this.name = name;
}
function getPromiseName(sex) {
return promise = $.ajax({
type: "GET",
url: "TMxml.xml",
dataType: "xml"//,
//async: false //this works for returns, but is apparently bad practice
});
}
function makeName(sex) {
var fnames = [];
var lnames = [];
var thexml = getPromiseName(sex);
thexml.done(function(xml) {
if (sex == "male") {
$(xml).find('malename').children().each(function(){
fnames.push($(this).text());
});
}
if (sex == "female") {
$(xml).find('femalename').children().each(function(){
fnames.push($(this).text());
});
}
$(xml).find('lastname').children().each(function(){
lnames.push($(this).text());
});
wholename = fnames[Math.floor(Math.random() * fnames.length)] + " " + lnames[Math.floor(Math.random() * lnames.length)];
alert("wholename = " + wholename); //successfully alerts a randomized name
return wholename; //but returns undefined, or [object Promise] when using async/await
});
}