【问题标题】:Return a value from inside a promisse [duplicate]从承诺中返回一个值[重复]
【发布时间】:2019-02-04 19:04:31
【问题描述】:

我有一个可以容纳其他对象的对象。

import Axios from "axios";

let API = {
    get:{
        dogPicture: () =>
        {   
            Axios.get("https://dog.ceo/api/breeds/image/random")
            .then(res => {
                //this.setState({wiseDog:res.data.message})
                //this.setState({isLoading:false})

            })
            .catch( err => {
                //this.setState({error:err.data.message})
            })
        },
        dogFact: () =>
        {
            Axios.get("/facts")
            .then( response => {
                //this.setState({DogFact:response.data.facts[0]})
                //this.setState({isLoading:false})
                return response.data.facts[0];
            })
            .catch( err => {
                console.log("still error", err)
                //this.setState({error:err})
                return err;
            })
        },
        test: () => "test"
    }
}  

export default API;

如果我导入它并调用

let message = API.get.test();

它将返回字符串测试。 但是,如果我尝试从我的dogPicture 或我的dogFact 的回复返回资源, 它返回undefined。 如果我尝试console.log(res),它会显示正确的预期值。

调用这些函数时如何返回从 res 和 response 获得的值?

【问题讨论】:

标签: reactjs jsx


【解决方案1】:

简单地说,你不能。 Javascript 是一种异步语言,“测试”以同步方式返回。因为你涉及到远程 API,我建议返回一个 Promise(添加 async 会将你的函数变成一个 Promise,并允许你使用 await):

import Axios from "axios";

let API = {
    get:{
        dogPicture: async () =>
        {   
            const res = await Axios.get("https://dog.ceo/api/breeds/image/random");

            return res.data;
        }
        test: () => "test"
    }
}  

export default API;

然后在你的代码中,你可以使用:

let message = await API.get.dogPicture();

【讨论】:

    猜你喜欢
    • 2021-06-29
    • 2015-02-13
    • 1970-01-01
    • 2020-08-26
    • 2015-10-27
    • 2015-11-27
    • 2018-03-10
    • 2015-12-16
    • 2014-05-21
    相关资源
    最近更新 更多