【问题标题】:'await' has no effect on the type of this expression'await' 对这个表达式的类型没有影响
【发布时间】:2020-06-07 14:48:15
【问题描述】:

我对此进行了搜索,但没有找到任何特定于我需要的东西。如果有的话,请在这里分享。

我正在尝试创建一个可以在各种组件中调用的通用服务。由于它是一个从外部源请求数据的函数,所以我需要将其视为异步函数。问题是,编辑器返回消息“'await' 对此表达式的类型没有影响”。而且应用确实崩溃了,因为还没有数据。

People.js 调用服务 requests.js

import React, { useEffect, useState } from "react";
import requests from "../services/requests";

export default () => {

   // State
   const [ people, setPeople ] = useState({ count: null, next: null, previous: null, results: [] });

   // Tarefas iniciais
   useEffect(() => {
       carregarpeople(1);
   }, []);

   // Carregando os dados da API
   const carregarpeople = async (pageIndex) => {
       const peopleResponse = await requests("people", pageIndex);

       // This line below needs to be executed but it crashes the app since I need to populate it with the data from the function requests
       // setPeople(peopleResponse);
   }


   return (
       <div>
       {
           people.results.length > 0 ? (
               <ul>
                   {
                       people.results.map(person => <li key = { person.name }>{ person.name }</li>)
                   }
               </ul>    
           ) : <div>Loading...</div>
       }
       </div>
   )
  }

这是 requests.js,它从 API 返回 json

export default (type, id) => {
console.table([ type, id ]);

fetch(`https://swapi.co/api/${type}/?page=${id}`)

.then(response => response.json())
.then(json => {
    console.log(json);
    return json;
})}

【问题讨论】:

    标签: javascript reactjs async-await


    【解决方案1】:

    如果你用打字稿得到这个,可能是因为你没有返回Promise

    例如:
    ❌不正确:

    async delPerson (id: string): Partial<Person> {
        return await this.personModel.findByIdAndRemove(id);
    }
    deletedPerson = await this.personService.delPerson(body._id);
    // in above line typescript thinks that he is awaiting for something which is not a promise
    

    ✅正确:

    async delPerson (id: string): Promise<Partial<Person>> {
        return await this.personModel.findByIdAndRemove(id);
    }
    deletedPerson = await this.personService.delPerson(body._id);
    

    【讨论】:

      【解决方案2】:

      我收到此错误只是因为我的 JSDoc 注释不正确。

      例如,我有一个 async 函数,它有 @returns {string}

        /**
         * Fetch from the swapi API
         *
         * @param {string} type
         * @param {string} id
         * @returns {string} JSON
         */
        export default async (type, id) => {
          console.table([ type, id ]);
          const response = await fetch(`https://swapi.co/api/${type}/?page=${id}`);
          const json = await response.json();
          console.log(json);
          return json;
        }
      

      我收到“'await' 对这个表达式的类型没有影响”警告 - 但函数看起来是正确的。

      但是,一旦我将 JSDoc 更改为 @returns {Promise&lt;string&gt;},错误就消失了:

        /**
         * Fetch from the swapi API
         *
         * @param {string} type
         * @param {string} id
         * @returns {Promise<string>} JSON
         */
      

      您也可以按照JSDoc documentation 的建议使用@async 提示:

      /**
       * Download data from the specified URL.
       *
       * @async
       * @function downloadData
       * @param {string} url - The URL to download from.
       * @return {Promise<string>} The data from the URL.
       */
      

      【讨论】:

      • 这个答案对我很有帮助。尽管它不适用于所讨论的问题,但它仍然是我的问题的解决方案。感谢发帖。
      【解决方案3】:

      我找到了解决方案。弹出此建议是因为您在等待之后放置了错误的对象。您可以通过在 await 关键字之后放置一个 Promise(不带括号)或一个返回 Promise 的函数来完全摆脱这种情况。

      【讨论】:

        【解决方案4】:

        await 仅在您将其与 Promise 一起使用时才有用,但 requests 不会返回 Promise。它根本没有返回语句,所以它隐式返回undefined

        看起来你的意思是让它返回一个承诺,所以这是你的代码,其中添加了返回:

        export default (type, id) => {
          console.table([ type, id ]);
          return fetch(`https://swapi.co/api/${type}/?page=${id}`)
            .then(response => response.json())
            .then(json => {
              console.log(json);
              return json;
            })
        }
        

        p.s,如果您更喜欢使用 async/await 执行此操作,它看起来像:

        export default async (type, id) => {
          console.table([ type, id ]);
          const response = await fetch(`https://swapi.co/api/${type}/?page=${id}`);
          const json = await response.json();
          console.log(json);
          return json;
        }
        

        【讨论】:

        • 太棒了。这就是解决方案。我认为已经存在的“return json”行是返回。但是return必须在fetch之前。谢谢尼古拉斯!
        猜你喜欢
        • 2023-01-20
        • 1970-01-01
        • 2013-06-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-02-08
        • 1970-01-01
        相关资源
        最近更新 更多