我正在更新我的Ajax来获取和阅读一些基本的获取示例以理解它。给出的示例经常使用箭头功能,当我试图学习新概念时,我的大脑会破裂。因此,我试图将其转换为标准的JavaScript功能,但它不起作用。实际上它有效,但没有返回JSON,而是返回“未定义”。

问题描述 投票:0回答:1

您遇到的问题是由于在您的标准JavaScript函数中,您没有返回

MyResults.json()
的结果。 
fetch

api依赖于每个API的返回值

.then()
将其传递到下一个
.then()
javascript fetch arrow-functions
1个回答
0
投票
.then()

将接收

undefined
在这里您可以修复代码:
箭头功能版本(工作)
fetch('https://reqres.in/api/users')
    .then(MyResults => MyResults.json())
    .then(MyData => console.log(MyData));
标准JavaScript函数(固定)
fetch('https://reqres.in/api/users')
    .then(
        function MyFunction1(MyResults) {
            return MyResults.json(); // Add `return` here
        }
    )
    .then(
        function MyFunction2(MyData) {
            console.log(MyData); // Now `MyData` will contain the JSON data
        }
    );

解释

arrow函数版本

MyResults => MyResults.json()
隐式返回

MyResults.json()

的结果。
    这个返回的承诺将传递给下一个
  1. .then()

    • 标准javascript函数
    • MyFunction1
    • ,您需要明确
      return
    • MyResults.json()
  2. 没有
  3. return

    MyFunction1返回

    undefined
      ,因此
    • MyFunction2
      接收
      undefined
      而不是json data。
      
      
      
    • 为什么
    • return
      很重要
      方法期望回调函数将返回将传递给下一个
      .then()
      的值(或承诺)。
      如果您不返回任何东西,那么下一个会收到
      .then()
      afling full示例带有错误处理
    • there是一个更完整的示例,使用错误处理
    .then()

undefined
确保正确处理响应的任何网络错误或问题。
    

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.