Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ES7async函数的用法 #9

Open
Abiel1024 opened this issue Apr 16, 2018 · 0 comments
Open

ES7async函数的用法 #9

Abiel1024 opened this issue Apr 16, 2018 · 0 comments

Comments

@Abiel1024
Copy link
Owner

Abiel1024 commented Apr 16, 2018

出现

异步操作是 JavaScript 编程的麻烦事,麻烦到一直有人提出各种各样的方案,试图解决这个问题。
最早的地域式回调,再到ES6的Promise链式调用,而到了ES7出现的async和await可以说是最优雅的实现了。之前大致看了下,觉得好麻烦,直到用了,才发现真的是一个好东西。

用法

function getUser() {
  return new Promise((resolve)=>{
    setTimeout(()=>{
      resolve('success')
    }, 3000)
  })
}

async function result(){
  const result = await getUser();
  console.log(result)
};
result();

间隔三秒之后打印出了success (用谷歌浏览器可以直接就跑出来!)
image

这边出现了async和await,可能接下来就说下这两个的具体含义和使用方法。

async

先从单词本身的含义来说:
image
在一个函数前面加上了这么一个单词,那么意义显而易见了,声明这个函数是异步的。

async用法
async返回的是一个promise对象:

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

const result = testAsync();
console.log(result);
result.then((test)=>{
    console.log(test)
})

image

实际应用:

function timeout(ms) {
  return new Promise((resolve) => {
    setTimeout(resolve, ms);
  });
}
async function asyncPrint(value, ms) {
  await timeout(ms);
  console.log(value)
}
asyncPrint('hello world', 1000);

利用async实现在多少时间之后输出hello world

await

image
从字面上就很好理解,等待。用于等待一个Promise 对象,但只能在异步函数 async function 中使用。可参考语法说明
但实际上,await只是在等待一个返回结果。它可以等任意表达式的结果,所以,await 后面实际是可以接普通函数调用或者直接量的。
可以看这个例子

function getSomething() {
  return "something";
}
async function testAsync() {
  return Promise.resolve("hello async");
}
async function test() {
  const v1 = await getSomething();
  const v2 = await testAsync();
  console.log(v1, v2);
}
test();

image
也是完全能运行的。

上面说的是正常情况下,但如果await函数中如果出错了呢?或者返回结果是rejected呢?
那么就可以这么处理:

async function myFunction() {
  try {
    await somethingThatReturnsAPromise();
  } catch (err) {
    console.log(err);
  }
}
// 另一种写法
async function myFunction() {
  await somethingThatReturnsAPromise().catch(function (err){
    console.log(err);
  });
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant