如何解决如何按特定顺序对.then调用进行排序?
我对诺言的概念还很陌生,我试图建立一个简单的口袋妖怪清单(又名pokedex)。我正在使用以下代码。
我希望根据它们的标记列出宠物小精灵的名字,我不希望被打扰。我当前使用的代码不能保证此功能。
在forEach()
方法中,fetch()
调用没有以任何方式链接,因此取决于首先收到哪个响应,但是我希望索引{{1}的then()
}将在索引x
的{{1}}之前执行。
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()
解决方法
您可以使用Promise.all
并传递第一个API调用的结果,这将按照请求的顺序返回响应:
const container = document.querySelector(".container");
fetch('https://pokeapi.co/api/v2/pokemon?limit=150')
.then(response => response.json(),e => {
console.error(e);
throw e;
})
.then(json => {
Promise.all(json.results.map(el => fetch(el.url)))
.then(arr => {
arr.map(response => response.json())
.forEach((result,index) => {
result.then(el => {
const pokemonName = el.name;
const pokemontype = el.types[0].type.name;
container.innerHTML += `(${index+1}) ${pokemonName} - ${pokemontype} <br>`;
})
})
}).catch(e => {
console.error(e)
throw e;
});
}).catch(e => {
console.error(e)
throw e;
});
<div class="container"></div>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。