问题描述
我正在尝试组合 .fetch()
、.then()
。和.all()
。但我做对了。我的情况是这样的:
-
fetch()
来自 API 的记录。 (我的物品) -
then()
在此记录中搜索更多 API 链接。 (在这里我可以找到属于该项目的媒体链接。每个项目可以有任意数量的媒体)。 -
all()
使用.fetch()
为每个链接执行 API 调用
-
then()
如果之前的所有 promise 都实现了,则执行渲染 依赖于这些数据的函数。
// Prepare Request Header
this.url_params = new URLSearchParams(window.location.search);
let httpHeader = {};
let request = new Request(api_itemURL + this.url_params.toString(),{
method: "GET",headers: new Headers(httpHeader),});
// The first fetch I have wrapped a seperate class. I still need it from other places.
omekaAPI
.getItemOnly(request)
.then(
function (result) {
this.itemObject = result;
let media_array = Array.from(result["o:media"],(x) => x["@id"]);
// Up to here it works wonderfully. I have list with all links. But after that it doesn't even jump into the all.
console.log(media_array);
return media_array;
}.bind(this)
)
.all(
media_array.map((media_array) =>
fetch(url).then(function () {
console.log("Its works!?!");
})
)
);
我不知道自己做错了什么,可以朝正确的方向推动。
后续问题
今天我尝试处理输入。不幸的是,我欢呼得太早了。我只取回了未填充的 Promise。我的循环当然不起作用。然后我尝试附加 .then()
。在 Promise.all()
内和在我假设的 .then()
之后。不幸的是,这具有相同的结果。我认为然后应该退后一步并阅读有关 Promise 的一般信息。我是否可能必须使用 await
/async
来执行此操作?但是我必须以不同的方式编写完整的函数,或者?此外,当我在里面有这些命令之一时,我的 babel/uglify 完全吓坏了。如果有人可以给我一个提示,如果我可以在这里使用我的代码去任何地方,那就太好了?
getItemWithAllMedia(request) {
return fetch(request)
.then((response) => {
return response.json();
})
.then((data) => {
console.log(data);
return data;
})
.then((result) => {
let media_links = Array.from(result["o:media"],(x) => x["@id"]);
return media_links;
})
.then((media_links) => {
return Promise.all(media_links.map((url) => fetch(url)));
})
.then((media_response) => {
/// debugging results from promise.all
console.log(media_response); // (2) [Response,Response]
console.log(media_reponse[0]); // ReferenceError: media_reponse is not defined
console.log(media_reponse[0].json()); // ReferenceError: media_reponse is not defined
/// desired function: all responses to json and push to an array
media_response.forEach((element) => {
media_data.push(element.json());
});
/// show created array for debugging
console.log(media_data);
return media_data;
})
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)