here和其他地方有很多解决方案,但是似乎很少解决将获取的文本或json数据实际保存到变量以供以后使用的简单问题。我有这个:
let ip;
const URL = 'https://api.ipify.org'
const userIp = ((url) => {
fetch(url)
.then(res => res.text())
.then(data => ip = data)
.then(() => console.log(ip)) // Logs the IP
})
// I want to use "ip" as a variable in the rest of my code
(console.log(ip) // naturally returns undefined
console.log(userIp(URL)) // Variations of this gives me the promise
我也尝试过以下变化:
const URL = 'https://api.ipify.org'
let userIp;
const getIp = (url) => {
return fetch (url)
.then( response => response.text())
.then( result => result)
}
let ip = getIp(URL)
.then(result => {
userIp = result
})
console.log(ip) // Promise <pending>
也尝试了异步/等待,结果相同,IP地址在函数内部记录得很好,但是在范围之外使用它是“不可能的”。
我还试图调用函数,该函数将从then()内部使用变量作为参数。但是也不能使它正常工作(此外,该变量还不能立即使用,应该由click事件触发)。
所以问题是:如何最好地获得一个IP变量来保存我的IP字符串以供脚本后面的其他函数使用?