首页 > 解决方案 > 使用异步等待让 .then 消失

问题描述

要求:

异步等待这一行: fetch(url).then(resp => resp.json())

所以不应该有任何 .then() 调用了!

原代码:

    const urls = [
  'https://jsonplaceholder.typicode.com/users',
  'https://jsonplaceholder.typicode.com/posts',
  'https://jsonplaceholder.typicode.com/albums'
]

const getData = async function() {
  const [ users, posts, albums ] = await Promise.all(urls.map(url =>
      fetch(url).then(resp => resp.json())
  ));
  console.log('users', users);
  console.log('posta', posts);
  console.log('albums', albums);
}
getData();

我在我的 JS 中尝试的内容:

 const [ users, posts, albums ] = await Promise.all(urls.map
 (url=>
     resp = await fetch(url);
     data = await resp.json();
 ));

我希望输出与原始代码相同

标签: javascriptasync-await

解决方案


您的函数不返回任何内容,并且未标记async(任何使用 的函数都需要await)。此外,不声明变量并不酷。

const [users, posts, albums] = await Promise.all(urls.map(async url => {
    const resp = await fetch(url);
    const data = await resp.json();
    return data;
}));

编辑:另外,guest271314 所说的 - 现在需要卷曲,因为内部函数不是一个简单的表达式。


推荐阅读