首页 > 解决方案 > 何时返回 fetch() 以及何时仅使用 fetch() 请求?

问题描述

我开始使用本机反应,我一直想知道的一件事是,有时我看到 fetch 是这样使用的:

createTodo(){
   fetch('http://192.168.1.34:3000/createTodo', {
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        content: this.state.noteText,
      }),
   }).then((response) => response.json())
      .then((responseJson) => {
        var d = new Date();
        this.state.noteArray.push({
            'date':d.getFullYear()+
            "/"+(d.getMonth()+1) +
            "/"+ d.getDate(),
            'note': responseJson.data.content
        });
        this.setState({ noteArray: this.state.noteArray });
        this.setState({noteText:''});

        console.log(responseJson);
      }).catch((error) => {
        console.error(error);
        console.log('Shit! Error occured');
      });
}

这项工作很好。

有时是:

return fetch(...)...

我有点困惑。

标签: react-nativefetch-api

解决方案


fetch是返回另一个 Promise 的 Promise。解析结果传递给下一个.then输入参数。因此,在您的示例代码中,您可以处理responsefetch函数传递的值。

fetch当客户createTodo想要使用 的“结果”时,您可以返回您的函数createTodo。“结果”是另一个 Promise,其输入参数来自createTodo的返回值

Demo只是为了展示Promise的返回值是另一个Promise。我希望你能得到提示。


推荐阅读