async and await 是promise的语法糖


More recent additions to the JavaScript language are async functions and the await keyword, added in ECMAScript 2017.

这些功能就是promises的语法糖,making asynchronous 代码容易写和读点。
他们让async code看山去想old-school的synchronous代码。
他们值得去学习。

The async keyword is added to functions to tell them to return a promise rather than directly returning the value.

await only works inside async functions within regular JavaScript code

Try typing the following lines into your browser's JS console:

there are a number of JavaScript libraries and frameworks that enable module usage (for example, other CommonJS and AMD-based module systems like RequireJS, and more recently Webpack and Babel).




function hello() { return "Hello" };
hello();

The function returns "Hello" — nothing special, right?

But what if we turn this into an async function? Try the following:

async function hello() { return "Hello" };
hello();

Ah. Invoking the function now returns a promise. This is one of the traits of async functions — their return values are guaranteed to be converted to promises.

You can also create an async function expression, like so:

let hello = async function() { return "Hello" };
hello();

And you can use arrow functions:

let hello = async () => "Hello";

These all do basically the same thing.
-------------------------------------------------------------
hello().then((value) => console.log(value))

or even just shorthand such as

hello().then(console.log)



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);
});


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));




阅读量: 544
发布于:
修改于: