LoginSignup
0
0

More than 3 years have passed since last update.

promise 与 await 的互换

Posted at

Rewriting promise code with async/await
Let's look back at a simple fetch example that we saw in the previous article:

fetch('coffee.jpg')
.then(response => {
if (!response.ok) {
throw new Error(HTTP error! status: ${response.status});
}
return response.blob();
})
.then(myBlob => {
let objectURL = URL.createObjectURL(myBlob);
let image = document.createElement('img');
image.src = objectURL;
document.body.appendChild(image);
})
.catch(e => {
console.log('There has been a problem with your fetch operation: ' + e.message);
});
By now, you should have a reasonable understanding of promises and how they work, but let's convert this to use async/await to see how much simpler it makes things:

async function myFetch() {
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);
}
}

myFetch()
.catch(e => {
console.log('There has been a problem with your fetch operation: ' + e.message);
});
It makes code much simpler and easier to understand — no more .then() blocks everywhere!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0