await only works inside of async functions
awaited promises happening
await 会阻止他后面的代码的执行,一直到the promise 执行完(fulfill).
Each await will wait for the previous one to finish,
whereas actually what you might want is for the promises to begin processing simultaneously, like they would do if we weren't using async/await.
await 会阻止他后面的代码的执行,一直到the promise 执行完(fulfill).
Each await will wait for the previous one to finish,
whereas actually what you might want is for the promises to begin processing simultaneously, like they would do if we weren't using async/await.
You can use a synchronous try...catch structure with async/await. This example expands on the first version of the code we showed above:
async function myFetch() { try { let response = await fetch('coffee.jpg'); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } let myBlob = await response.blob(); let objectURL = URL.createObjectURL(myBlob); let image = document.createElement('img'); image.src = objectURL; document.body.appendChild(image); } catch(e) { console.log(e); } } myFetch();
async function myFetch() { let response = await fetch('coffee.jpg'); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } return await response.blob(); } myFetch().then((blob) => { let objectURL = URL.createObjectURL(blob); let image = document.createElement('img'); image.src = objectURL; document.body.appendChild(image); }) .catch((e) => console.log(e) );
async function fetchAndDecode(url, type) { let response = await fetch(url); let content; if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } else { if(type === 'blob') { content = await response.blob(); } else if(type === 'text') { content = await response.text(); } } return content; } async function displayContent() { let coffee = fetchAndDecode('coffee.jpg', 'blob'); let tea = fetchAndDecode('tea.jpg', 'blob'); let description = fetchAndDecode('description.txt', 'text'); let values = await Promise.all([coffee, tea, description]); let objectURL1 = URL.createObjectURL(values[0]); let objectURL2 = URL.createObjectURL(values[1]); let descText = values[2]; let image1 = document.createElement('img'); let image2 = document.createElement('img'); image1.src = objectURL1; image2.src = objectURL2; document.body.appendChild(image1); document.body.appendChild(image2); let para = document.createElement('p'); para.textContent = descText; document.body.appendChild(para); } displayContent() .catch((e) => console.log(e) );
阅读量: 617
发布于:
修改于:
发布于:
修改于: