JS Fetch – 数据未定义 – promise

huangapple go评论71阅读模式
英文:

JS Fetch - data is undefined - promise

问题

以下是翻译好的部分:

我想要分析来自HTTP请求的回答,如果需要的话显示错误,然后返回数据。

这是我目前正在做的事情:

fetch(URL, { method: "GET" })
    .then(async response => { await read_errors(response) })
    .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;

    // 检查错误响应
    if (!response.ok) {
        // 从主体获取错误消息,或默认为响应状态
        const error = (data && data.message) || text || response.status;
        console.error("出现错误:", error);
        return Promise.reject(error);
    } else {
        fckng_response = isJson ? data : text
        return Promise.resolve(fckng_response)
    }
}

但我得到了 TypeError: data is undefined 的错误。

服务器的回应包含正确的标头和数据。

我做错了什么?

英文:

I want to analyse anwser from http request, display error if needed then return data.

This is what I'm doing right now:

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) })

With this function :

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)
	}
}

But I've got TypeError: data is undefined

The answer from server is all right with headers and data OK.

What am I doing wrong?

答案1

得分: 2

你没有在`.then`回调中返回调用`read_errors`的结果要么添加一个返回语句要么删除花括号{})。

.then(response => read_errors(response))
// 这里不需要异步
更简单的方法是完全使用async和await不要将它与回调混合使用

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

You're not returning the result of calling read_errors in the .then callback. Either add a return statement or remove the braces ({}).

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

It is simpler to completely work with async and await, without mixing it with callbacks.

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

答案2

得分: 0

为了解决这个问题,您需要从read_errors()函数中返回数据。以下是修改后的代码:

fetch(URL, { method: "GET" })
  .then(response => read_errors(response))
  .then(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;

  if (!response.ok) {
    const error = (data && data.message) || text || response.status;
    console.error("Something went wrong:", error);
    throw error; // 使用throw而不是Promise.reject
  } else {
    const fckng_response = isJson ? data : text;
    return fckng_response;
  }
}
英文:

To fix this issue, you need to return the data from the read_errors() function. Here's the modified code:

fetch(URL, { method: "GET" })
  .then(response => read_errors(response))
  .then(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;

  if (!response.ok) {
    const error = (data && data.message) || text || response.status;
    console.error("Something went wrong:", error);
    throw error; // Use throw instead of Promise.reject
  } else {
    const fckng_response = isJson ? data : text;
    return fckng_response;
  }
}

huangapple
  • 本文由 发表于 2023年7月17日 20:41:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/76704557.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定