【问题标题】:React/Express: Inserting an if-statement inside a response promise?React/Express:在响应承诺中插入 if 语句?
【发布时间】:2019-01-25 00:15:38
【问题描述】:

我收到了一个从 POST 调用到 express 后端的承诺响应。我想在 Promise 中插入一个 if 语句,这似乎违反了它。

这行得通:

fetch('http://localhost:8000/upload', {
    method: 'POST',
    body: formData,
})
    .then(response =>
        response.json())
    .then(response => {
        console.log(response);
    })

这个 if else 语句破坏了代码:

fetch('http://localhost:8000/upload', {
        method: 'POST',
        body: formData,
    })
        .then(response => {
            if (response.ok) {
                response.json()
            } else {
                throw new Error('Something went wrong ...');
            }
        })
        .then(response => {
            console.log(response);
        })

这样的事情可能吗?提前致谢!

【问题讨论】:

    标签: javascript reactjs express post promise


    【解决方案1】:

    如果一个箭头函数只有一个语句并且没有{}围绕它的主体,这将被隐式地视为返回值。因此,在您的第一个示例中,response => response.json() 将隐式返回 response.json() 的结果。

    但是,如果您添加 {} 括号,它将不再是隐式返回。在这种情况下,它是否包含if 块甚至都没有关系。在定义包裹到{} 的主体时,需要显式返回response.json() 的结果:

    response => {
        // explicit return needed
        if (response.ok) {
            return response.json();
        }
    }
    

    From the MDN docs

    箭头函数可以有一个“简洁的主体”或通常的“块” 身体”。

    在简洁的正文中,只指定了一个表达式,它成为 显式返回值。在块体中,您必须使用显式 return 声明。

    var func = x => x * x;                  
    // concise body syntax, implied "return"
    
    var func = (x, y) => { return x + y; }; 
    // with block body, explicit "return" needed
    

    【讨论】:

      【解决方案2】:

      您没有在 if 块中返回 response.json。因此,在下一个 then 方法中,您没有定义 response。试试这个:

      fetch('http://localhost:8000/upload', {
              method: 'POST',
              body: formData,
          })
              .then(response => {
                  if (response.ok) {
                      return response.json()
                  } else {
                      throw new Error('Something went wrong ...');
                  }
              })
              .then(response => {
                  console.log(response);
      })
      

      【讨论】:

      • 也谢谢你!
      猜你喜欢
      • 2014-03-21
      • 1970-01-01
      • 1970-01-01
      • 2020-10-19
      • 2016-05-31
      • 2020-08-20
      • 2021-07-13
      • 2019-06-13
      相关资源
      最近更新 更多