所以我意识到我在这里有一个范围问题。我正在使用API来返回电影列表。响应包括一系列电影对象。每个电影对象都有一个字符数组,但每个字符只是一个端点。目标是列出每部电影与该特定电影相关的前3个字符。什么是最有效的方法来实现这一目标?这是我目前的代码,我知道这是错误的,但应该传达我想要做的相当清楚的事情。
import {getCharByUrl, getFilms} from './api/swapiApi';
getFilms().then(result => {
let films = result.results; // Array of films
let episodes = ``;
films.forEach(film => {
let urls = film.characters; // Array of endpoints to hit
let chars = `<ul>`;
for (let i = 0; i < 3; i++) {
getCharByUrl(urls[i]).then(character => {
chars += `<li>${character.name}</li>`;
});
}
chars += `</ul>`;
episodes += `
<div class="col-sm-4">
<div>${film.title}</div>
<div>${film.director}</div>
${chars}
<hr>
</div>
`;
});
global.document.getElementById('films').innerHTML = episodes;
});
对我有用的代码:
import {getCharByUrl, getFilms} from './api/swapiApi';
getFilms().then((result) => {
let films = result.results; // Array of films
let episodes = ``;
var Promise = require('es6-promise').Promise;
films.forEach((film) => {
let urls = []; // Array of endpoints to hit
for(let i = 0; i < 3; i++) {
urls.push(film.characters[i]);
}
let chars = `<ul class="list-unstyled">`;
Promise.all(urls.map((url) => {
return getCharByUrl(url);
})).then((data) => {
// data will be an array of the responses from all getCharByUrl requests
data.forEach((character) => {
chars += `<li>${character.name}</li>`;
});
chars += `</ul>`;
}).then(() => {
episodes += `
<div class="col-sm-4">
<div>${film.title}</div>
<div>${film.director}</div>
${chars}
<hr>
</div>
`;
global.document.getElementById('films').innerHTML = episodes;
});
});
});
答案 0 :(得分:0)
我看看Promise.all:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all。没有看到api响应但不是肯定的,但我认为你可以这样做:
import {getCharByUrl, getFilms} from './api/swapiApi';
getFilms().then((result) => {
let films = result.results; // Array of films
let episodes = ``;
films.forEach((film) => {
let urls = film.characters; // Array of endpoints to hit
let chars = `<ul>`;
Promise.all(urls.map((url) => {
return getCharByUrl(url);
})).then((data) => {
// data will be an array of the responses from all getCharByUrl requests
data.forEach((character) => {
chars += `<li>${character.name}</li>`;
});
chars += `</ul>`;
}).then(() => {
episodes += `
<div class="col-sm-4">
<div>${film.title}</div>
<div>${film.director}</div>
${chars}
<hr>
</div>
`;
global.document.getElementById('films').innerHTML = episodes;
});
});
});