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

更优雅的处理异步方式 -- async await #34

Open
chenyinkai opened this issue Mar 21, 2018 · 0 comments
Open

更优雅的处理异步方式 -- async await #34

chenyinkai opened this issue Mar 21, 2018 · 0 comments

Comments

@chenyinkai
Copy link
Owner

async await

async

表示函数中存在异步操作

// 语法
async function name(params) {
  statements
}

await

await 只能在 async 函数中使用, 表示需要等待后面的表达式返回结果

// 语法
returnValue = await expression

注意 await 后面的 Promise 有可能返回的是 rejected, 所以最好把 await 放在 try···catch 中, 方便错误处理

try {
    await expression
  } catch (err) {
    console.log(err)
  }

demo

function test() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      console.log('status:resolve')
      resolve('resolve')
    }, 2000)
  })
}

async function async() {
  console.log('asyncfn start')
  let result = await test()
  console.log(result)
}

async()

function testFn(x) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(x)
    }, 2000)
  })
}

async function asyncFn(x) {
  let a = await testFn(10)
  let b = await testFn(20)
  console.log(`${x}+${a}+${b}`)
}

asyncFn(30).then(() => {
  console.log('asycnFn finished')
})
@chenyinkai chenyinkai changed the title 更好的处理异步操作--async await 更优雅的处理异步方式 -- async await Mar 21, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant