【发布时间】:2018-06-10 13:53:58
【问题描述】:
我已经嵌套了 axios 调用,因此使用 Promise 来构建我将用于我的应用程序的数据数组。
第一次调用获取标题或剧集列表。
第二次调用获取第一次收到的剧集 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()'s 中的任何内容 -
@charlietfl 你能给我看一个修改上面代码的例子吗?
-
@charlietfl 我正在映射的数组,我正在 Promise 中更新。您能解释一下为什么在控制台记录sections 数组时会出现这些值,但在第三次调用中执行项目属性时却没有。
-
首先,仅在需要的地方使用 Promise - 代码的快速而肮脏的重写(我认为)是 jsfiddle.net/r7txrqo0 - 注意只有一个 Promise.all ...与 5 个不必要的 Promise 相比.all 在您的代码中? ...并使用 forEach,因为您的代码中根本不需要 .map - 然而,这是一个快速而肮脏的重写
-
你的代码可以写成jsfiddle.net/r7txrqo0/1 - 老实说,我仍然不理解或不喜欢第一个“循环”。而且,最后,
dataService将是一个解析为undefined的 Promise,与您的原始代码相同 - 因为我不知道您希望dataService实际上是什么
标签: javascript arrays reactjs es6-promise axios