我有一個像下面這樣包含 itemId 的陣列。我想遍歷陣列并為每個 itemId 從 API 獲取相應的資料,然后收集結果并渲染 DOM。不能讓它作業....
gtinArray = [
"07314224054620",
"07314225267340",
"07313929649155",
"07314226417799",
"07314226224342"
]
getItem(gtin) {
return new Promise((resolve, reject) => {
const URL = "http://localhost:7071/api/GetItem?Gtin=" gtin
fetch(URL)
.then(result => result.json())
.then(item => {
resolve(item)
})
})
}
pupulateCart() {
let itemRequests = []
gtinArray.forEach(gtin => {
itemRequests.push(getItem(gtin))
})
Promise.all(itemRequests)
.then(allItemData => {
console.log("All item data")
console.log(allItemData)
})
}
uj5u.com熱心網友回復:
const gtinArray = ["1", "2", "3", "4", "5"]
function getItem(gtin) {
const URL = "https://jsonplaceholder.typicode.com/todos/" gtin
return fetch(URL).then(response => response.json());
}
async function populateCart() {
let itemRequests = []
itemRequests = gtinArray.map(gtin => getItem(gtin));
return await Promise.all(itemRequests)
}
(async function () {
const data = await populateCart();
console.log(data);
})();
uj5u.com熱心網友回復:
這可能是您的問題,您的getItem函式格式不正確。此外,任何異步呼叫都需要包含在異步函式中。
gtinArray = [
"07314224054620",
"07314225267340",
"07313929649155",
"07314226417799",
"07314226224342"
]
const getItem = (gtin) => {
return new Promise((resolve, reject) => {
const URL = "http://localhost:7071/api/GetItem?Gtin=" gtin
fetch(URL)
.then(result => result.json())
.then(item => {
resolve(item)
})
})
}
async function pupulateCart() {
let itemRequests = []
gtinArray.forEach(gtin => {
itemRequests.push(getItem(gtin))
})
Promise.all(itemRequests)
.then(allItemData => {
console.log("All item data")
console.log(allItemData)
})
}
pupulateCart();
uj5u.com熱心網友回復:
具有承諾的解決方案,不需要 async/await(盡管如果您更喜歡這種風格,則可以輕松轉換)。
const gtinArray = [
"07314224054620",
"07314225267340",
"07313929649155",
"07314226417799",
"07314226224342"
]
function getItem(gtin) {
const URL = "http://localhost:7071/api/GetItem?Gtin=" gtin
// next line is to remove the external server and just give us the URL back
// (just for the sake of StackOverflow example)
return Promise.resolve(URL)
// next line is what you'd actually want to make the fetch and convert json
// return fetch(URL).then(result => result.json())
}
function populateCart() {
// return promise, or caller can't chain
// (even if allItemData is processed in .then())
return Promise.all(gtinArray.map(gtin => getItem(gtin)))
.then(allItemData => {
console.log("All item data")
console.log(allItemData)
})
}
populateCart().then(() => console.log('done'));
uj5u.com熱心網友回復:
首先,非常感謝您的幫助,非常感謝!
我現在已經根據以下更新了我的代碼。不幸的是,我仍然無法正常作業。當我單擊觸發 populateCart() 函式的按鈕時,console.log("Running populateCart") 是唯一被記錄到控制臺的東西。我可以在服務器端處理所有五個請求,但會話似乎永遠不會關閉。如果我殺死服務器,每次獲取都會出現控制臺錯誤。請參閱隨附的螢屏。

import { LitElement, html, css} from 'lit'
import './button-done'
import './cart-item'
import { Client } from './client'
import { Queue } from './queue'
const { ipcRenderer } = window.require('electron')
export class GateApp extends LitElement {
static get properties() {
return {
title: { type: String },
customer: { type: String },
email: { type: String },
items: {type: Object},
gtinArray: {type: Object},
}
}
static get styles() {
return css`
:host {
min-height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: flex-start;
font-size: calc(10px 2vmin);
color: #1a2b42;
max-width: 960px;
margin: 0 auto;
text-align: center;
background-color: var(--gate-app-background-color);
}
.frame2 {
background-color: #CAEEC2;
}
#pageLayout {
width: 100vw;
height: 100vh;
display: flex;
flex-direction: column;
}
#frameTop {
width: 100%;
height: 50px;
}
#frameLeft {
width: 50px;
height: calc(100vh - 100px);
}
#frameRight {
width: 50px;
height: calc(100vh - 100px);
}
#frameBottom {
width: 100%;
height: 50px;
}
#centerRow {
display: flex;
flex-direction: row;
}
#content {
width: calc(100vw - 100px);
height: calc(100vh - 100px);
display: flex;
flex-direction: column;
justify-content: center;
}
#cartItemContainer {
width: calc(100vw - 100px);
display: flex;
flex-wrap: wrap;
flex-direction: row;
justify-content: center;
align-content: flex-start;
}
.cart-item {
margin: 15px;
box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.2), 0 4px 20px 0 rgba(0, 0, 0, 0.19);
border-radius: 5px;
}
`
}
constructor() {
super()
this.title = 'Shoppingbag'
this.customer = ''
this.email = ''
this.items = []
//this.gtinArray = []
this.gtinArray = ['07314224178272', '07314227150152', '07314227475811', '07314228873272', '07314227368533']
this.client = new Client()
this.gtinQueue = new Queue()
this.timer
}
firstUpdated() {
ipcRenderer.on("new-scan", (_, tag) => {
//console.log("Received message from Electron: ", tag)
if (this.isBag(tag)) {
} else {
this.handleScan(tag)
}
})
}
render() {
return html`
<div id="pageLayout">
<div id="frameTop" class="frame"></div>
<div id="centerRow">
<div id="frameLeft" class="frame"></div>
<div id="content">
<h1>${this.title}</h1>
<div id="cartItemContainer">
${this.items.map(item => html`
<cart-item
class="cart-item"
imageUrl="${item.assetUrl}"
itemName="${item.productName}"
itemPrice="${item.whitePrice}"
artNr="${item.articleId}"
size="Medium"
></cart-item>
`)}
</div>
<br>
<button-done @click="${this.populateCart}"></button-done>
</div>
<div id="frameRight" class="frame"></div>
</div>
<div id="frameBottom" class="frame"></div>
</div>
`
}
itemInCart(gtin) {
let itemInCart = false
this.items.forEach(item => {
if (item.gtin === gtin) {
itemInCart = true
}
})
return itemInCart
}
isBag(tag) {
if (tag.substring(0, 2) === '00')
return true
else
return false
}
handleScan(tag) {
var found = false
this.gtinArray.forEach(gtin => {
if (gtin == tag) {
found = true
}
})
if(!found) {
this.gtinArray.push(tag)
this.gtinQueue.enqueue(tag)
clearTimeout(this.timer)
this.runTimer()
console.log(this.gtinArray)
}
}
getItem = (gtin) => {
return new Promise((resolve, reject) => {
const URL = "http://localhost:7071/api/GetItem?Gtin=" gtin
fetch(URL)
.then(result => result.json())
.then(item => {
resolve(item)
})
})
}
async populateCart() {
console.log("Running populateCart")
let itemRequests = []
this.gtinArray.forEach(gtin => {
itemRequests.push(this.getItem(gtin))
})
Promise.all(itemRequests)
.then(allItemData => {
console.log("All item data")
console.log(allItemData)
})
}
}
customElements.define('gate-app', GateApp)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/477783.html
標籤:javascript 异步
