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

es7 async / await 简单示例 #5

Open
WangShuXian6 opened this issue Apr 20, 2018 · 2 comments
Open

es7 async / await 简单示例 #5

WangShuXian6 opened this issue Apr 20, 2018 · 2 comments
Labels

Comments

@WangShuXian6
Copy link
Owner

es7 async / await

function asyncF(name) {
	return new Promise((resolve, reject) => {
		setTimeout(() => {
			resolve('my name is ' + name)
		}, 1000)
	})
}

function sum(a, b) {
	return new Promise((resolve, reject) => {
		setTimeout(() => {
			resolve(a + b)
		}, 1000)
	})
}

async function fn() {
	const line = await asyncF('tom')
	const n = await sum(2, 3)
	console.log(line + ':' + n)
}
//2秒后终端显示
//my name is tom:5
@WangShuXian6
Copy link
Owner Author

####错误处理

test() {
      return new Promise((reslove, reject) => {
        if(true){
          reject('wrong')
        }else{
          reslove('right')
        }
      })
    }



async asyncBegin() {
      let num = await this.test().catch((error)=>{
        console.log(error)
      })
      console.log('num', num)
    }

//wrong
//num undefined

@WangShuXian6
Copy link
Owner Author

####串行执行异步

test1()
async test1(){
      await this.test2()
      await this.test3()

    }

    async test2(){
      let code=await this.test4()
      console.log(code)
    }

    async test3(){
      let code=await this.test5()
      console.log(code)
    }

    test4(){
      return new Promise((resolove,reject)=>{
        setTimeout(()=>{
          resolove(3000)
        },3000)
      })
    }

    test5(){
      return new Promise((resolove,reject)=>{
        setTimeout(()=>{
          resolove(2000)
        },2000)
      })
    }

// 3000
// 2000

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant