承诺实现中的未定义错误

Undefined Error Within a Promise Fulfilled

我正在调用 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 需要return一个承诺。

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 new Promise((resolve, reject) => {
        fetch( queryPath )
            .then(( response ) => response.json( ))
            .then(( data ) => {
                console.log( "data is...", data );
                resolve(data);
            })
            .catch(( err ) => {
                reject(err);
                console.log( err );
            })
    })
};

export default getWeather;

您的 getWeather() 函数没有 return 任何东西。您需要 return 您那里的承诺链产生的承诺。

你的函数目前也在吞噬错误,所以我在你的 .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( ));
};