我搜索了此内容,但没有找到我需要的特定内容。如果有一个,请在这里分享。

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

People.js调用服务request.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 - &#39;await&#39;对此表达式的类型没有影响-LMLPHP

最佳答案

await仅在与 promise 一起使用时才有用,但requests不会返回 promise 。它根本没有return语句,因此它隐式返回undefined

看起来您是要让它返回 promise ,所以这是添加了返回值的代码:

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;
    })
}

ps,如果您更喜欢使用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;
}

关于javascript - 'await'对此表达式的类型没有影响,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60368017/

10-12 00:00
查看更多