如何按特定顺序对.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>

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...