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

时间:2019-05-27 19:15:55

标签: javascript node.js promise async-await

我试图以异步等待形式从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
}

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

2 个答案:

答案 0 :(得分:2)

您显然正在使用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
}

答案 1 :(得分:1)

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