I am currently trying to use an API to get IP addresses for visitors. I am getting a "promise pending" message when using the following code:
function getIPAdd(){ var ip = fetch('https://pro.ip-api.com/json/?key=KEY').then(response => response.json()).then(data => data); return ip; } var ipAdd = getIPAdd(); console.log(ipAdd); I get this output:
Promise {<pending>} __proto__: Promise [[PromiseState]]: "fulfilled" [[PromiseResult]]: Object This means that the promise is ebing fulfilled but for some reason, still is not completed?
While if I use the following code:
(function(){ fetch('https://pro.ip-api.com/json/?key=KEY').then(response => response.json()).then(data => console.log(data)); })(); I do not get any "promise pending" issues. I am guessing this is becasue it is due to the way console.log is used in the latter code sample but how can I fix the first code sample so I get my JSON output the way I need it.
thenis only called after the fetch completes butreturn ipgets executed first before the function insidethen. Thethenmethon is how you are supposed to return a valuevar ipadd = getIpAdd(); ipadd.then(console.log)async function x () { var ipadd = await getIpAdd(); console.log(ipadd) } ; x().thens you can useawait, but that is only possible inside anasyncfunction. (And this async function itself will then return a Promise.) You can't fully synchronize asynchronous code.