【问题标题】:being able to use data with fetch api request and error checking能够通过获取 api 请求和错误检查来使用数据
【发布时间】:2021-10-23 11:08:02
【问题描述】:

尝试通过错误检查发出 API 请求,然后能够在异步函数之外使用来自 API 的数据。这正在返回一个未决的承诺。不知道如何从 API 中获取可用数据,然后我可以在整个程序中进一步使用。有什么建议吗?

const fetch = require('node-fetch')

const url = 'https://employeedetails.free.beeceptor.com/my/api/path'

async function getData(url){
    try {
        const response = await fetch(url)
        if (!response.ok) {
            throw new Error ("why did I become a software engineer?");
        }
        else {
            return await response.json();
        }
    }
    catch (error) {
        console.log(error);
    }
}

const data = getData(url);
console.log(data);

【问题讨论】:

    标签: javascript api error-handling async-await fetch-api


    【解决方案1】:

    async 函数返回一个承诺。要获得可用数据,您必须await getData(url)(为此创建另一个异步函数)或者在您的示例中您可以编写:

    getData(url).then(data => console.log(data);
    

    【讨论】:

      【解决方案2】:

      我认为这里的问题是异步函数正在返回一个承诺,因此您应该添加另一个异步函数来获取该数据,或者您应该在函数之前添加一个全局变量然后更改其值

      【讨论】:

        猜你喜欢
        • 2018-10-02
        • 2016-07-19
        • 2019-10-31
        • 1970-01-01
        • 2018-09-06
        • 1970-01-01
        • 1970-01-01
        • 2018-02-05
        • 1970-01-01
        相关资源
        最近更新 更多