是的,我已经尝试过其他解决方案,但没有成功。我尝试在 promise 之上设置一个变量(区域),但意识到它超出了范围,所以这是我的下一个解决方案。每当我尝试返回区域时,它都会返回为未定义。每当我console.log它(在同一个地方)它工作得很好。对此有何见解?
编辑:iplocation 是一个 npm 包 iplocation
function getRegion(ipAddr) {
iplocation(ipAddr)
.then(res => {
if (res.country == 'US') {
region = res.country + "-" + states[res.region_code];
} else {
region = res.country;
}
return region;
})
}
最佳答案
async function getRegion (ipAddr) {
let res
try {
res = await iplocation(ipAddr)
if (res.country === 'US') {
return `${res.country} - ${states[res.region_code]}`
} else {
return res.country
}
} catch (err) {
throw err
}
}
用法:
getRegion('8.8.8.8')
.then(loc => console.log(loc))
.catch(err => console.log(err))
关于node.js - Promise 返回 undefined variable ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51460894/