我正在嘗試回傳 fetch 呼叫的結果,但我想等到我的 eventListener 檢測到動態呈現的選擇器串列中的更改。
您將看到下面撰寫的 fetch 呼叫從 API 中獲取值并呈現值串列。我想知道是否有一種方法可以防止這種.then(resp => resp.json())情況發生,直到為 selectList 偵聽器做出選擇為止。我最終希望得到結果的值。然后承諾,以便我可以在將來的另一個 fetch 呼叫中使用它。
鏈接到codepen
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dynamic List Test</title>
</head>
<body>
<div >
<!-- App entry point -->
</div>
<script type="text/javascript" src="app.js"></script>
</body>
</html>
const testUrl =
'https://hub.dummyapis.com/employee?noofRecords=10&idStarts=1001';
const result = fetch(testUrl, {
method: 'GET',
})
.then(resp => resp.json())
.then(data => {
// Create select list
const mainEl = document.querySelector('.container');
let selectList = document.createElement('select');
selectList.id = 'selectorList';
mainEl.appendChild(selectList);
// // Prepare name list
let nameArray = [];
const nameList = data;
nameArray.push(nameList);
console.log(nameArray[0]);
for (let last in nameArray[0]) {
let surname = nameArray[0][last].lastName;
let option = document.createElement('option');
option.value = surname;
option.text = surname;
selectList.appendChild(option);
}
let selectorChoice = '';
// Grab dynamic selector value
selectList.addEventListener('change', e => {
selectorChoice = e.target.value;
console.log(selectorChoice);
return selectorChoice;
});
})
.then(resp => resp.json()) // I want to wait for the eventListener to be called before this happens
.catch(error => console.log('Error:', error));
result.then(resp => {
console.log(resp);
});
結果在控制臺
(10) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]0: {id: 1001, imageUrl: 'https://hub.dummyapis.com/Image?text=CA&height=120&width=120', firstName: 'Colt', lastName: 'Altenwerth', email: '[email protected]', …}1: {id: 1002, imageUrl: 'https://hub.dummyapis.com/Image?text=HW&height=120&width=120', firstName: 'Helena', lastName: 'Ward', email: '[email protected]', …}2: {id: 1003, imageUrl: 'https://hub.dummyapis.com/Image?text=LC&height=120&width=120', firstName: 'Liliana', lastName: 'Connelly', email: '[email protected]', …}3: {id: 1004, imageUrl: 'https://hub.dummyapis.com/Image?text=MH&height=120&width=120', firstName: 'Myah', lastName: 'Hane', email: '[email protected]', …}4: {id: 1005, imageUrl: 'https://hub.dummyapis.com/Image?text=MS&height=120&width=120', firstName: 'Mauricio', lastName: 'Stracke', email: '[email protected]', …}5: {id: 1006, imageUrl: 'https://hub.dummyapis.com/Image?text=CS&height=120&width=120', firstName: 'Candice', lastName: 'Sipes', email: '[email protected]', …}6: {id: 1007, imageUrl: 'https://hub.dummyapis.com/Image?text=EA&height=120&width=120', firstName: 'Evangeline', lastName: 'Aufderhar', email: '[email protected]', …}7: {id: 1008, imageUrl: 'https://hub.dummyapis.com/Image?text=RR&height=120&width=120', firstName: 'Rosetta', lastName: 'Rodriguez', email: '[email protected]', …}8: {id: 1009, imageUrl: 'https://hub.dummyapis.com/Image?text=TD&height=120&width=120', firstName: 'Tina', lastName: "D'Amore", email: "Tina.D'[email protected]", …}9: {id: 1010, imageUrl: 'https://hub.dummyapis.com/Image?text=PS&height=120&width=120', firstName: 'Pearline', lastName: 'Sawayn', email: '[email protected]', …}length: 10[[Prototype]]: Array(0)
app.js:37 Error: TypeError: Cannot read properties of undefined (reading 'json')
at app.js:36:22
app.js:40 undefined
app.js:32 Hane
uj5u.com熱心網友回復:
把它分成三個步驟。
- 準備:獲取資料 快取資料
const fetchResult = fetch(...).then(response => response.json());
- 構建串列(使用 id 來識別記錄!)
fetchResult.then(data => {
// Create select list
const mainEl = document.querySelector('.container');
let selectList = document.createElement('select');
selectList.id = 'selectorList';
mainEl.appendChild(selectList);
data.forEach(employee => {
const option = document.createElement('option');
option.value = employee.id;
option.text = employee.lastName;
selectList.appendChild(option);
});
let selectList.addEventListener('change', e => {
selectorChoice = parseInt(e.target.value);
handleUserChoice(data, selectorChoice)
});
}
)
- 處理用戶選擇基于
id
function handleUserChoice(data, id) {
const chosenEmployee = data.find(e => e.id === id);
if (choosenEmployee) {
// ... do what you want here!
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/495975.html
標籤:javascript es6-承诺 获取 API
下一篇:在forEach回圈中繼續
