我想分析一个从http请求,显示错误,如果需要,然后返回数据.

这就是我现在正在做的事情:

fetch(URL,{method:"GET"})
.then(async response => { await read_errors(response) })
// .then(response => { read_errors(response) }) (Both had been tried)
.then( function(data) { 
    doSomething(data)
})
.catch( error => { display_error(error) })

使用此功能:

async function read_errors(response) {
    const isJson = response.headers.get('content-type')?.includes('application/json');
    const data = isJson ? await response.json() : null;

    const isText = response.headers.get('content-type')?.includes('text/');
    const text = isText ? await response.text() : null;

    // check for error response
    if (!response.ok) {
        // get error message from body or default to response status
        const error = (data && data.message) || text || response.status;
        console.error("Something went wrong : ",error)
        return Promise.reject(error);
    } else {
        fckng_response = isJson ? data : text
        return Promise.resolve(fckng_response)
    }
}

但我有TypeError: data is undefined

来自服务器的答案是正确的,头和数据都是正常的.

我做错了什么?

推荐答案

您不会在.then回调中返回呼叫read_errors的结果.添加返回语句或删除大括号({}).

.then(response => read_errors(response))
// no need for async here

完全使用异步和等待会更简单,而不会与回调混在一起.

try {
    const response = await fetch(URL);
    const data = await read_errors(response);
    doSomething(data);
} catch (error) {
    display_error(error);
}

Javascript相关问答推荐

ChartJS:分组堆叠条形图渲染错误

订阅操作顺序

如何在alpinejs中显示dev中x-for的元素

nPM审计始终发现0个漏洞

如果没有尾随斜线,托管在收件箱中的React/Vite将无法工作

在NextJS中使用计时器循环逐个打开手风琴项目?

如何从对象嵌套数组的第二级对象中过滤出键

使用JavaScript在ionic Web应用程序中更新.pane和.view的背景 colored颜色

硬币兑换运行超时

如何在RTK上设置轮询,每24小时

如何将Map字符串,布尔值转换为{key:string;value:bo布尔值;}[]?<>

函数返回与输入对象具有相同键的对象

分层树视图

显示图—如何在图例项上添加删除线效果?

为什么我的导航条打开状态没有在窗口addeventlistener(Reaction Js)中更新?

映射类型定义,其中值对应于键

使用getBorbingClientRect()更改绝对元素位置

Puppeteer上每页的useProxy返回的不是函数/构造函数

在VS代码上一次设置多个变量格式

React Refs不与高阶组件(HOC)中的动态生成组件一起工作