I have the following object, stored in a variable ($gameSystem._ipLookupJSON
):
{
"www.geoplugin.net/json.gp?jsoncallback=?": {
"IP": "geoplugin_request",
"Country": "geoplugin_countryCode",
"City": "geoplugin_city"
},
"gd.geobytes.com/GetCityDetails?callback=?": {
"IP": "geobytesipaddress",
"Country": "geobytescountry",
"City": "geobytescity"
},
"ip-api.com/json": {
"IP": "ip",
"Country": "country_name",
"City": "city"
},
"ipinfo.io/json": {
"IP": "ip",
"Country": "country",
"City": "city"
}
}
Each of the keys in this object is a URL.
I have a function ($._findService()
) that:
Goes through each of these keys and sends them to another function (
$._urlExists()
), which checks if the URL is valid / responsive,If true,
$._findService()
creates a new array with only the key and its elements,- And is supposed to return this new array.
Unfortunately, I am having problems with the third step- returning the new array.
I have Google'd and read as much as I can about Promises, .then, and Async/Await, but I just cannot figure it out and am at my wit's end just staring at these lines of code.
const isServiceAvailable = async url_to_check => {
console.log(url_to_check);
return await subaybay.an._urlExists("http://" + url_to_check);
};
const checkServices = async(json_data) => {
return await Promise.all(Object.keys(json_data).map(url_to_check => isServiceAvailable(url_to_check)));
};
$._findService = function(json_data) {
var url_check = checkServices(json_data);
url_check.then(function(values) {
for (i = 0; i < values.length; i++) {
if (values[i] === true) {
var service_to_use = new Promise(function(resolve, reject) {
var result = [];
result.push(json_data[Object.keys(json_data)[i]]);
result.unshift(Object.keys(json_data)[i]);
resolve(result);
});
service_to_use.then(function(value) {
console.log(value);
return value;
});
};
};
});
};
I am hoping for $._findService()
to return an array.
But alas all I get is undefined
.
I apologize if my code is not elegant or pretty- I have only been teaching myself JavaScript since the end of February.
Your problem was that you wasn't returning anything in the function scope and you should have return the promise(s).
You can then use:
or
Note: when you return something from an async function you will get a promise, so, when you use await you are awaiting for the promise result inline.
There isn't and never will be any disadvantage to use async and await over a Promise, and, it's modern and better since you don't make more nested functions using "then" or "new Promise" syntax.