gpt4 book ai didi

javascript - 调用一个获取 API 并呈现返回值的函数,Promises 出现问题

转载 作者:行者123 更新时间:2023-12-02 22:32:43 25 4
gpt4 key购买 nike

在shoppingView.js中,我想为“items”中的每个“item”渲染一个 block ,但是我得到的是一个 promise ,而不是函数调用中的值,格式是json。如何从数组中检索所有项目并渲染它们?---> 检查 ShoppingView render() 中的注释

我知道“.then()”、“async/await”,但我不知道在处理返回 Promise 的函数时如何思考。我可以强制函数返回一个值而不是一个值吗?调用时promise并让程序等待?

感谢所有帮助:)

半伪代码..

storeModel.js - 处理 api 调用等

class StoreModel {
constructor() {
this.items = [];
}

getItems() {
return this.items;
}

getItem(id) {
const res = fetch(ENDPOINT + '/grocery/' + id + '/information/', {
"method": "GET",
"headers": {
"Host": ENDPOINT,
"Key": API_KEY,
}
})
.then(res => {
if(res.ok) {
console.log("SUCCESS");
return res.json();
} else {
console.log("UNSUCCESSFUL");
return res.json()
}
})
.then({
data => return data
})
.catch(error => {
console.log(error);
});
return res;
}

addItem(item) {
this.items.push(item);
}
}

app.js

window.onload = function () {
const cont = document.body.querySelector("#container");
const model = new StoreModel();

Promise.all([
model.addItem(model.getItem(1)),
model.addItem(model.getItem(2)),
model.addItem(model.getItem(3)),
])
.then(
new HomeView(cont, model).render();
new ShoppingView(cont, model).render();
});
}

shoppingView.js

class ShoppingView {
constructor(container, model) {
this.container = container;
this.model = model;
}

render() {
this.container.appendChild(document.createElement('h3').textContent = "Items";
var div = this.container.appendChild(document.createElement('div'));

/* GET THE VALUE OF items HERE */

/* I'VE TRIED ********************************
var items = this.model.getItems();
----> item.title etc, is undefined
**********************************************/
for(let item of items {
div.appendChild(document.createElement('img')).setAttribute('src', item.image);
div.appendChild(document.createElement('h4')).textContent = item.title;
}
}
}

最佳答案

storeModel.js

// remove syntactically incorrect and redundant handler
.then({ data => return data }) // should be .then(data => data) (no curly braces or return)

model.getItem 始终返回一个 Promise,需要在访问该值之前对其进行解析,即。

model.getItem(id).then(item => {
// do something with item... eg.
model.addItem(item);
});

您传递给 model.addItem 的值是一个 promise ,而不是一个 item,因此您正在使用 Promise 填充项目列表。 model.addItem 返回 undefined,因此在 app.jsPromise.all 正在尝试解析 [未定义,未定义,未定义]。由于您不关心 Promise.all 的结果,请考虑以下方法:

app.js

Promise.all([1, 2, 3].map(id => {
return model.getItem(id).then(item => model.addItem(item))
})).then((items) => {
new HomeView(cont, model).render();
new ShoppingView(cont, model).render();
});

结果将是[undefined, undefined, undefined],但您无论如何都不需要它,因为这些项目已经添加到model.items中。

关于javascript - 调用一个获取 API 并呈现返回值的函数,Promises 出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58842380/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com