繁体   English   中英

我得到承诺{ <pending> }作为返回值,并在异步作用域中调用,立即给我未定义的信息

[英]I get Promise { <pending> } as returned value and also calling in async scope gives me undefined immediately

我试图以异步等待形式从Promise中返回一个值,并在另一个文件中的另一个函数中使用它,但是我确实有问题,因为Promise没有返回任何值。 当我尝试console.log('website')时,它立即返回undefined(就像根本没有从API服务中获取值一样)。 我不知道自己在做什么错,我真的很喜欢学习Promises和Async-Await,但是每次尝试与他们合作时,我都会感到更加困惑。

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`
    });
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM