async/await question

I have a function that SHOULD get an IP-address and when found, return it. It doesn´t work: it doesn´t wait, ip-address comes back as undefined and function returns a promise. I am doing something wrong, but what? Anyone?

export async function chkIpAddress () {
const httpResponse = await fetch(‘https://extreme-ip-lookup.com/json’, {
method: ‘get’
});

	if (httpResponse.ok) { 
		const json =  httpResponse.json(); 
		const ipaddress = json.query; 

console.log(“ipadress after getting it=” + ipaddress);
return ipaddress;
}
}

1 Like

Try to await the others as well.

const json =  await httpResponse.json();
const ipaddress = await json.query;

Hi Andreas, tried that, but it still doesn´t wait. I call it with:

let strIpAddress = chkIpAddress();

and now function is:

export async function chkIpAddress () {
const httpResponse = await fetch(‘https://extreme-ip-lookup.com/json’, {
method: ‘get’
});

	if (httpResponse.ok) { 
		const json = await httpResponse.json(); 
		const ipaddress = await json.query; 

console.log(“ipadress after getting it=” + ipaddress);
return ipaddress;
}
}

The function returns a Promise, goes on with the next step, and after a while, at the very end, the console.log with the ip-address is logged, correctly, but too late.

let strIpAddress = chkIpAddress()
.then(function(results) {
console.log(res);
})

Andreas, thanks, but, with minor changes (res/result) still not working. Still this function is not waiting, it kicks in after all is done (=too late).

Tried this?
return await ipaddress;

Up, me too, I would like the solution of the story please

Did you make it work? If could you share solution.

async await solution:

import {fetch} from ‘wix-fetch’ ;

$w.onReady( function () {
callIP();
});

async function callIP(){
const response = await fetch( ‘https://extreme-ip-lookup.com/json’ );
const objectIP = await response.json();
console.log(objectIP);
}

the method by default is always GET, so you don’t need to set the method

call this kind of function and use DEV tools on your browser to extract from the objectIP whatever you need, since this is an object you can do objectIP.city or any other …