我正在努力兑现承诺。到目前为止,我个人喜欢使用async / await和try / catch块,因为它对我个人而言是可读的。
但是我仍然坚持使用Promise.all
。
这是我用于练习的数据。
const starWars = [
'https://swapi.co/api/people/1',
'https://swapi.co/api/people/2',
'https://swapi.co/api/people/3',
'https://swapi.co/api/people/4'
];
我感觉我必须在异步函数中使用.map()
,但是一直遇到错误。
所以我的问题是。使用async / await,Promise.all和try / catch块从这些url中获取数据的方法是什么?
将每个URL映射到fetch
调用,然后在.json
承诺中调用fetch
:
const urls = [
'https://swapi.co/api/people/1',
'https://swapi.co/api/people/2',
'https://swapi.co/api/people/3',
'https://swapi.co/api/people/4'
];
(async () => {
try {
const allResponses = await Promise.all(
urls.map(url => fetch(url).then(res => res.json()))
);
console.log(allResponses[0]);
} catch(e) {
console.log(e);
// handle errors
}
})();
我更喜欢抓住函数之外的地方,我认为它看起来更简洁并且需要更少的缩进:
const urls = [
'https://swapi.co/api/people/1',
'https://swapi.co/api/people/2',
'https://swapi.co/api/people/3',
'https://swapi.co/api/people/4'
];
(async () => {
const allResponses = await Promise.all(
urls.map(url => fetch(url).then(res => res.json()))
);
console.log(allResponses[0]);
// do stuff with allResponses
})()
.catch((e) => {
console.log(e);
// handle errors
});
如果您只有一个地方需要等待Promise解决,您也可以考虑完全放弃async
函数(这在IMO中看起来会更好:]
const urls = [
'https://swapi.co/api/people/1',
'https://swapi.co/api/people/2',
'https://swapi.co/api/people/3',
'https://swapi.co/api/people/4'
];
Promise.all(
urls.map(url => fetch(url).then(res => res.json()))
)
.then((allResponses) => {
console.log(allResponses[0]);
// do stuff with allResponses
})
.catch((e) => {
console.log(e);
// handle errors
});
您可以使用map
功能为所有网址创建承诺,然后通过Promise.all
等待它们>
const starWars = [
'https://swapi.co/api/people/1',
'https://swapi.co/api/people/2',
'https://swapi.co/api/people/3',
'https://swapi.co/api/people/4'
];
const promises = starWars.map(url => fetch(url).then(res => res.json());
Promise.all(promises).then(results => /*Resolved code*/)
.catch(error => /*Rejected code*/);
const starWars = [
'https://swapi.co/api/people/1',
'https://swapi.co/api/people/2',
'https://swapi.co/api/people/3',
'https://swapi.co/api/people/4'
];
async function makeApiCalls() {
try {
let res = await Promise.all(starWars.map(endpoint => fetch(endpoint)));
// depending on content-type apply .json() .blob() etc
console.log(response);
} catch (err) {
console.error(err);
}
}