javascript - 使用异步等待让 .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();
));
我希望输出与原始代码相同
解决方案
您的函数不返回任何内容,并且未标记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 所说的 - 现在需要卷曲,因为内部函数不是一个简单的表达式。
推荐阅读
- javascript - 将字符串解析为 xml 时丢失了一些内容
- .net - $.connection.hub.start().done() 上的错误 500
- php - 从 Google My Business 获取 PHP 的营业时间
- ruby-on-rails - 将甜蜜警报绑定到动态添加的元素
- python-3.7 - 有什么办法可以解决argv解包问题
- python - 如何根据特定条件(包括 DateTime)映射来自多个 Pandas Dataframe 的值?
- sql - 使用 NOT EXISTS 重写查询的指南
- go - 如何使用 shopify sarama 通过抵消来处理消费者恢复
- node.js - 节点:从目录中删除所有文件的正确方法是什么?
- java - spring-amqp 与 ibm jvm 的兼容性