【问题标题】:why i keep getting undefined when i console.log this function为什么当我 console.log 这个函数时我一直不确定
【发布时间】:2021-10-30 23:40:56
【问题描述】:

您好,我是 node js 的完整初学者,我刚刚了解了 Promise,我正在尝试在我的代码中使用它们 但是当我尝试 console.log 这个函数时,我一直没有定义,我不知道为什么 如果你能帮助我,我将非常感激

function weather(location) {
    const request = require('request');
    const errorMessage = 'Something went wrong. Please check you internet connection or the URL you provided.';
    new Promise((resolve, reject) => {

        const geoUrl = `https://api.mapbox.com/geocoding/v5/mapbox.places/
    ${location}.json?access_token=pk.eyJ1Ijoic3F1YXJlc2NyaXB0IiwiYSI6ImNrc3lwZmdtejFpdzQycHB1eTVpODNwdmYifQ.izw6cVMKDZme4KJwxHdxjw`;

        request({
            url: geoUrl,
            json: true
        }, (error, request) => {
            if (error) {
                reject(errorMessage)
            } else {
                resolve(`http://api.weatherstack.com/current?access_key=
            c704f108fc10fbbdb15c384daff85a20&query=${request.body.features[0].center.reverse()}`)
            }
        })
    }).then(url => {
        request({
            url: url,
            json: true
        }, (error, request) => {
            if (error) {
                return errorMessage
            } else {
                const currData = request.body.current;
                return `${currData.weather_descriptions[0]}, It's currently ${currData.temperature} degrees out. There is a ${currData.humidity}% chance of rain.`;
            }
        });
    }).catch(message => message)
};
console.log(weather('NYC'))

【问题讨论】:

  • 您似乎错过了“return”语句,它应该是 return new Promise(...) 我认为您不需要用 Promise 包装请求,因为它已经返回了一个 Promise .看看promise chaining,它会让代码看起来更漂亮

标签: javascript node.js


【解决方案1】:

你需要回报承诺..

return new Promise((resolve,reject)=>{

然后控制台将记录“未解决的承诺”。或类似的东西。如果你想等待promise解决,你需要使用await或者then方法:

weather('NYC').then(console.log)

您还需要确保您的承诺被解决或拒绝:

if (error){reject(errorMessage)}
else {
    const currData=request.body.current;
    resolve(`${currData.weather_descriptions[0]}, It's currently ${currData.temperature} degrees out. There is a ${currData.humidity}% chance of rain.`);
}

如果您的代码格式正确,所有这些小错误都会更容易发现。

另外,请勿将您的私人访问令牌放在公共论坛中。

您可以在互联网上找到很多关于 Promise 如何工作的教程。这是MDN manual page

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-03
    • 1970-01-01
    • 1970-01-01
    • 2014-04-19
    • 1970-01-01
    • 2023-04-03
    • 1970-01-01
    相关资源
    最近更新 更多