首页 > 解决方案 > 如何解决“刚刚评估了以下值。” 对于链式 then 函数

问题描述

标签: javascriptecmascript-6es6-promise

解决方案


您正确地使用了 Pomise 来包装第一个 API 调用,但是您没有包装计时器和其他 API 调用,因此承诺在它们完成之前就解决了。现代浏览器支持fetch()比 更容易使用XMLHttpRequest,并且它已经返回了一个可以轻松链接的 Promise。现在唯一剩下的就是包装超时:

 const delay = ms => new Promise(res => setTimeout(res, ms));

现在我们有了所有这些 Promise,Promise.all并且可以使用链接来组合它们:

 const pokemonList = fetch(  "https://pokeapi.co/api/v2/pokemon/?limit=4" ).then(res => res.json());

 const pokemonDetails = pokemonList.then(list => {
   return delay(3000).then(() => {
     return Promise.all(list.results.map(pokemon => {
       return fetch(pokemon.url).then(res => res.json());
    });
  });
 });

推荐阅读