我得到 Promise { <pending> } 作为返回值,并且在异步范围内调用会立即给我未定义



我试图以异步等待形式从承诺中返回一个值,并在另一个文件的另一个函数中使用它,但我确实有问题,因为我的承诺没有返回任何值。 当我尝试控制台.log('网站')时,它会立即返回我未定义(就像根本没有从 API 服务中获取值一样)。我不知道我做错了什么,我真的很喜欢学习承诺和异步等待,但每次我试图与他们合作时,我都会变得更加困惑。

const dns = require('dns')
const iplocation = require("iplocation").default;
const emojiFlags = require('emoji-flags');
const getServerIPAddress = async (server) => {
return new Promise((resolve, reject) => {
dns.lookup(server, (err, address) => {
if (err) throw reject(err);
resolve(address);
});
});
};

const getServerLocation = async (server) => {
const ip = await getServerIPAddress(server)
iplocation(ip).then((res) => {
const country = emojiFlags.countryCode(res.countryCode)
const result = `Location: ${country.emoji} ${country.name}`
return result
})
.catch(err => {
return `Location: Unknown`
});
}
(async function() {
console.log(await getServerLocation('www.google.com'))
})()

module.exports = {
getServerLocation
}

对我来说,首先从这个函数中获取结果,然后在另一个函数中使用它的值非常重要。我希望你能给我一些关于如何异步执行任务的提示。

你显然正在使用async所以你为什么也使用then并不明显。如果您使用then则还必须返回承诺以保留承诺链:

const getServerLocation = async (server) => {
const ip = await getServerIPAddress(server)
return iplocation(ip).then((res) => {
const country = emojiFlags.countryCode(res.countryCode)
const result = `Location: ${country.emoji} ${country.name}`
return result
})
.catch(err => {
return `Location: Unknown`
});
}

否则,只需异步此内容:

const getServerLocation = async (server) => {
const ip = await getServerIPAddress(server)
let res = await iplocation(ip);
const country = emojiFlags.countryCode(res.countryCode)
const result = `Location: ${country.emoji} ${country.name}`
return result
}
const getServerLocation = async (server) => {
const ip = await getServerIPAddress(server)
//you need to return
return iplocation(ip).then((res) => {
const country = emojiFlags.countryCode(res.countryCode)
const result = `Location: ${country.emoji} ${country.name}`
return result
})
.catch(err => {
return `Location: Unknown`
});
}

最新更新