【问题标题】:Understanding the .then of a fetch [duplicate]了解 .then 的 fetch [重复]
【发布时间】:2020-08-10 18:16:18
【问题描述】:

我试图了解用于获取 fetch.then 捕获。目前我有以下我知道有效的 POST 请求。当我检查data 变量时,有一个数据数组。

fetch(`http://PRIVATE/stocks/authed/${query}?from=${convertedStart}T00%3A00%3A00.000Z&to=${convertedEnd}T00%3A00%3A00.000Z`, requestOptions) 
        .then(response => response.json())
        .then(data => setStockData(data));

我想应用一些错误处理,我试图在下面的以下更新代码中进行。但是,一旦我这样做了,data 变量就不再像上面的原始代码那样填充数据数组。为什么会这样,我该如何解决?

 fetch(`http://PRIVATE/stocks/authed/${query}?from=${convertedStart}T00%3A00%3A00.000Z&to=${convertedEnd}T00%3A00%3A00.000Z`, requestOptions) 
        .then(response => {
          if(!response.ok){
            if(response.status === 404){
              setError("Stock symbol not found please try again");
            }
            else{
              setError("Please check your connection to the database");
            }
          }
          else {
            return response.json();
          }
        })
        .then(data => setStockData(data));

【问题讨论】:

  • 您确定响应中有 200 代码吗?也许响应包含正确的数据,但状态码不是ok
  • setError 是做什么的?

标签: javascript fetch response


【解决方案1】:

因为将响应解码为 JSON 的 return response.json() 位于 else 内。

你可以想象那里有一个return undefined

fetch(`http://...`, requestOptions)
  .then(response => {
    if (!response.ok) {
      if (response.status === 404) {
        setError("Stock symbol not found please try again");
      } else {
        setError("Please check your connection to the database");
      }
    } else {
      return response.json();
    }
    return undefined;
  })
  .then(data => setStockData(data));

如果您确实希望始终(尝试)解码 JSON,尽管响应状态为 OK,请打开最后一个 else

【讨论】:

    【解决方案2】:

    then() 方法返回一个 promise,您可以在 PROMISE 阅读更多内容

    回到您的问题,您应该实现如下所示的内容。然后采取两个回调,一个代表成功,另一个代表拒绝,您可以利用它们来处理响应。

      fetch(`http://PRIVATE/stocks/authed/${query}?from=${convertedStart}T00%3A00%3A00.000Z&to=${convertedEnd}T00%3A00%3A00.000Z`, requestOptions)
            .then((successReponse) => {
    
                //If you have to handle status codes 
                if (successReponse.code == "200") {
                    //assuming success value has something called data which you want to set
                    setStockData(successResponse.data);
                }
                else if (true /* OTHER CODE HANDLER */) {
    
                }
    
            }, (rejected) => {
                //If there was a error you can handle here
            });
    

    【讨论】:

      猜你喜欢
      • 2020-07-28
      • 1970-01-01
      • 2019-01-29
      • 2011-06-13
      • 1970-01-01
      • 2015-09-10
      • 2021-03-21
      • 1970-01-01
      • 2016-01-21
      相关资源
      最近更新 更多