【发布时间】:2020-12-01 08:39:50
【问题描述】:
我对承诺的概念相当陌生,我正在尝试建立一个简单的口袋妖怪列表(又名 pokedex)。我正在使用以下代码。
我希望根据宠物小精灵的指示列出它们的名称,我不希望顺序受到干扰。我目前使用的代码不保证这个功能。
在forEach() 方法中,fetch() 调用不会以任何方式链接,因此这取决于首先收到哪个响应,但我希望索引x 的then() 在then() 之前执行索引x+1。
const container = document.querySelector(".container");
fetch('https://pokeapi.co/api/v2/pokemon?limit=150')
.then(response => response.json())
.then(json => {
json.results.forEach((el, index) => {
fetch(el.url)
.then(response => response.json())
.then(json => {
const pokemonName = el.name;
const pokemontype = json.types[0].type.name;
container.innerHTML += `(${index+1}) ${pokemonName} - ${pokemontype} <br>`;
})
})
})
<div class="container"></div>
更新:下面是我使用
Promise.all()的解决方案
const container = document.querySelector(".container");
fetch('https://pokeapi.co/api/v2/pokemon?limit=150')
.then(response => response.json())
.then(json => {
const responseArr = [];
json.results.forEach(el => {
responseArr.push(fetch(el.url));
});
return Promise.all(responseArr);
})
.then(responses => {
const jsonArr = [];
responses.forEach(el => {
jsonArr.push(el.json());
});
return Promise.all(jsonArr);
})
.then(jsons => {
jsons.forEach((json, index) => {
const pokemonName = json.name;
const pokemonType = json.types[0].type.name;
container.innerHTML += `(${index+1}) ${pokemonName} - ${pokemonType} <br>`;
});
})
<div class="container"></div>
【问题讨论】:
-
将promise放入一个数组中,然后使用
Promise.all()按照数组的顺序处理结果。 -
使用
Promise.all()或async/await
标签: javascript promise es6-promise