Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/xpath/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 取回承诺_Reactjs_Promise_Async Await_Fetch - Fatal编程技术网

Reactjs 取回承诺

Reactjs 取回承诺,reactjs,promise,async-await,fetch,Reactjs,Promise,Async Await,Fetch,我需要有关获取功能的帮助。 我有movie\u tyres\u url返回 const movie_genres_url = { "genres": [ { "id": 28, "name": "Action" }, { "id": 12, "name": "Adventure"

我需要有关获取功能的帮助。 我有
movie\u tyres\u url
返回

const movie_genres_url = {
  "genres": [
    {
      "id": 28,
      "name": "Action"
    },
    {
      "id": 12,
      "name": "Adventure"
    },
]
}
我有
genresArray
用于过滤

const genresArray= [28, 18, 53];
作为回报,我得到了一个承诺
Promise{}
但是我想要一个数组

['drama','action']


async
函数将返回一个
Promise
。因此,尽管看起来您正在返回值,但最终会返回一个
承诺

异步函数总是返回一个承诺。如果异步函数的返回值不是显式的承诺,它将隐式地包装在承诺中

下面是
获取
异步等待
的示例

const getData=async()=>{
let res=等待获取(“https://reqres.in/api/users?page=2");
让data=wait res.json();
返回数据;
}
getData()
.then(r=>{console.log(r)})

.catch(e=>{console.log(e)})
是否要从
move\u genres\u url
数组返回
genresArray
中匹配项的
name
s?这是您面临的问题还是其他问题?使用
fetch
的函数是异步的,不能立即返回值。返回承诺是解决方案,不是问题。@n这是肯定的,我还想返回
genres
作为array not promise。如果您想使用函数
fetchMovieGenres
,那么是
。然后(…)
wait
就是解决方案。


const fetchMovieGenres = async genresArray => {
  const response = await fetch(movie_genres_url);
  const json = await response.json();

  const genres = await json.genres
    .filter(genre => genresArray.includes(genre.id))
    .map(genre => genre.name);

  return genres;
};