首页 > 解决方案 > 'await' 对这个表达式的类型没有影响

问题描述

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

我正在尝试创建一个在各种组件中调用的通用服务。由于它是一个从外部源请求数据的函数,所以我需要将其视为一个异步函数。问题是,编辑器返回消息“'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;
})}

在此处输入图像描述

标签: javascriptreactjsasync-await

解决方案


我收到这个错误只是因为我的 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<string>},错误就消失了:

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

您还可以@async按照JSDoc 文档的建议使用提示:

/**
 * 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.
 */

推荐阅读