javascript - '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;
})}
解决方案
我收到这个错误只是因为我的 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. */
推荐阅读
- r - 如何修复 dplyr 包中的汇总函数错误?
- flutter - Dart-lang,我如何映射列表
列出 结合元素? - tensorflow - KubeFlow 上的 TFServing 和 KFServing 有什么不同
- node.js - 当流量通过 Cloudflare 路由时,WebSocket 连接从未完全建立
- django - 如何在 Django 中加载引导程序?
- python - read_csv 读取值包含在另一个数据框的列中的行
- python - 如何在 Python 中获得负十进制数的十进制平方根?
- java - QueryString 用冒号搜索字符串
- javascript - 计数和比较
- python - 未找到 webdrivermanager pip3