내 응용 프로그램에 사용할 데이터 배열을 구축하기 위해 약속을 사용하여 중첩 된 호출이 있습니다.배열 값은 사용할 수 없지만 console.log에 표시됩니다.
첫 번째 호출은 헤더 또는 에피소드 목록을 가져옵니다.
두 번째 호출은 추가 데이터를 얻기 위해 처음 수신 한 에피소드 URL을 사용합니다. 그런 다음 응용 프로그램에서 사용하려는 데이터 배열에 속성을 추가합니다. 다음은 title 및 image_urls [0]입니다.
그런 다음 세 번째 호출은 image_urls [0]을 취해 실제 이미지를 검색하기 위해 호출을 수행합니다. 이제는이 호출에서 console.log 나 두 번째 호출에 추가 된 값을 가진 작업을 수행 할 때 정의되지 않습니다. 그러나 console.log 내 전체 배열에 값이 표시됩니다!
console.log("sections", sections); // show all the data including 2nd call
console.log("image url", item.url); // This shows
console.log("image title", item.title); // This doesn't and don't know why
console.log("image imageurls", item.imageurls); // This doesn't and don't know why
여기 내 코드
import axios from 'axios';
let sections = new Array(),
section = null,
episodes = null;
const dataService =
axios
.get('http://feature-code-test.skylark-cms.qa.aws.ostmodern.co.uk:8000/api/sets/coll_e8400ca3aebb4f70baf74a81aefd5a78/items/')
.then((response) => {
var data = response.data.objects;
Promise.all(data.map(function (item) {
let type = item.content_type.toLowerCase();
if (type !== "episode") {
if (section !== null) {
section.episodes = episodes;
sections.push(section);
}
section = new Object();
episodes = new Array();
section.header = item.heading;
}
if (type === "episode") {
var episode = new Object();
episode.url = item.content_url;
episodes.push(episode)
}
})).then(function() {
section.episodes = episodes;
sections.push(section);
Promise.all(sections.map(function (item) {
Promise.all(item.episodes.map(function (item) {
var url = `http://feature-code-test.skylark-cms.qa.aws.ostmodern.co.uk:8000${item.url}`
axios
.get(url)
.then((response) => {
var data = response.data;
item.title = data.title;
item.imageurls = data.image_urls[0] !== undefined ? data.image_urls[0] : "";
});
}))
})).then(function() {
Promise.all(sections.map(function (item) {
Promise.all(item.episodes.map(function (item) {
console.log("sections", sections);
console.log("image urr", item.url);
console.log("image title", item.title);
console.log("image imageurls", item.imageurls);
}));
}));
});;
})
})
export default dataService
당신은'map()'을 계속 사용하지만 매핑 된 배열에는 아무 것도 반환하지 않습니다. 'Promise.all ([undefined, undefined])'은 쓸모가 없어서 아무것도 기다리지 않습니다. 또한 체인 된'then()'에서 아무 것도 반환하지 않음 – charlietfl
@charlietfl 위의 코드를 수정하는 예제를 보여줄 수 있습니까? – Adam
@charlietfl 내가 매핑하는 배열 나는 약속 안에서 업데이트 중입니다. 세 번째 호출에서 항목 속성을 수행 할 때 섹션 배열을 콘솔에 기록 할 때 값이 나타나는 이유를 설명 할 수 있습니까? – Adam