javascript - promise 履行中的未定义错误

标签 javascript reactjs promise fetch es6-promise

我正在调用 openweathermap api 来检索 higher-order 组件中的天气,然后渲染“Main”组件。但是,ajax调用成功后,出现以下错误:

TypeError: _getWeather2.default(...) is undefined

代码:

MainContainer.js:

import React from "react";
import getWeather from "../action/getWeather";
import Main from "./Main";

const MainContainer = () => {
// the error is somewhere related to this component
    var weather = getWeather( "london", "uk" )
        .then(( data ) => {
            console.log( "data in maincontainer is...", data );
            return <Main />;
        });
}

export default MainContainer;

getWeather.js:

const getWeather = ( city, country ) => {
    let queryPath = `http://api.openweathermap.org/data/2.5/forecast?q=${ city },${ country }&APPID=${ inserytKey }&mode=json`
    console.log( "queryPath is...", queryPath );
    fetch( queryPath )
        .then(( response ) => response.json( ))
        .then(( data ) => {
            console.log( "data is...", data );
            return data;
        })
        .catch(( err ) => {
            console.log( err );
        })
};

export default getWeather;

我做错了什么?

最佳答案

您的 getWeather() 函数不会返回任何内容。您需要返回由您那里的 promise 链生成的 promise 。

您的函数当前也在吞没错误,因此我在您的 .catch 处理程序中添加了一个 throw err:

const getWeather = ( city, country ) => {
    let queryPath = `http://api.openweathermap.org/data/2.5/forecast?q=${ city },${ country }&APPID=${ inserytKey }&mode=json`
    console.log( "queryPath is...", queryPath );

    return fetch( queryPath )
        .then(( response ) => response.json( ))
        .then(( data ) => {
            console.log( "data is...", data );
            return data;
        })
        .catch(( err ) => {
            console.log( err );
            throw err;
        })
};

如果您决定不需要使用 console.log 来记录 data 值,则可以删除第二个 .then。对于 .catch() 也是如此:

const getWeather = ( city, country ) => {
    let queryPath = `http://api.openweathermap.org/data/2.5/forecast?q=${ city },${ country }&APPID=${ inserytKey }&mode=json`
    console.log( "queryPath is...", queryPath );

    return fetch( queryPath )
        .then(( response ) => response.json( ));
};

关于javascript - promise 履行中的未定义错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43850969/

相关文章:

javascript - 如果我明确返回一个 Promise,我应该定义异步函数吗?

node.js - Promise.all 调出 "TypeError: undefined is not iterable (cannot read property Symbol(Symbol.iterator))"

javascript - 空/空白打印页

javascript - 为什么 react-native-onboarding-swiper 不能在我的启动画面上工作?

javascript - 是 var { Route, Redirect, RouteHandler, Link } = Router;在 Javascript 中有效吗?

javascript - 比较两个字符串并返回两者都不存在的值

javascript - 在自定义 promise 上使用异步等待

javascript - 如何使用 OData 模型将两个数据属性直接绑定(bind)到一个控件属性?

javascript - 为什么路由器会破坏 Angular2 中的生命周期钩子(Hook)?

javascript - Gulpfile 仅高效编译已更改的 TypeScript 文件