從Promise 到 generator 再到 async & await 一步跨過

Promise 處理異步代碼相對於純回調函數比較有序明瞭,可是對於同步函數寫法仍是挺繁瑣的,下面有兩種語法糖讓異步更加清晰簡潔promise

生成器

generator 函數

像指針同樣下移,有點像在debug代碼異步

function* gen() {
	yield 1
	yield 2
	yield 3
}
let g = gen()
console.log(g.next())
console.log(g.next())
console.log(g.next())
console.log(g.next()) 
複製代碼

  • 中斷並完成下移return()
function* gen() {
	yield 1
	yield 2
	yield 3
}
let g = gen()
console.log(g.next())
console.log(g.next())
console.log(g.return('完成'))
console.log(g.next()) 
複製代碼

  • 中斷並拋出異常 throw()
function* gen() {
	try {
		yield 1
		yield 2
		yield 3
	} catch(e) {
		console.log(e)
	}

}
let g = gen()
console.log(g.next())
console.log(g.next())
console.log(g.throw('異常'))
console.log(g.next()) 
複製代碼

若是在異步函數裏面使用 generator 函數怎樣?

function promise() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
          resolve('resolved')
    }, 1000)
  })
}

function* generate() {
 	promise().then((res) => {
    console.log(res)
  })
}

function fn() {
  const res = generate().next()
  console.log(res)
}

fn()
複製代碼

如今發現,異步代碼不須要then回調了,看起來和同步函數寫法同樣async

不過如今咱們有了asyncawait函數,將生成器進一步封裝,也能夠說出語法糖函數

async、await函數

使用Promise 寫法寫一個簡單的例子ui

function promise() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
          resolve('resolved')
    }, 1000)
  })
}

function fn() {
 	promise().then((res) => {
    console.log(res)
  })
}

fn()
複製代碼

改寫成 async 函數spa

async function asyncFn() {
  console.log(await promise())
}

asyncFn()
複製代碼

async 和 then 同樣 能夠達到同一個的效果,並且代碼中沒有回調函數的影子了debug

多條異步鏈的狀況3d

function promise() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
          resolve(1)
    }, 1000)
  })
}

function fn() {
 	const p =  promise().then((res) => {
    	console.log('第一個then', res)
    	return res === 2 ? new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve(2)
        }, 500)
   	 	}) : new Promise((resolve, reject) => {
        setTimeout(() => {
          reject(3)
        }, 500)
   	 	})
  }).then((res) => {
    console.log('第二個then', res)
  }).catch((err) => {
    console.log('異常', err)
  })
}

fn()
複製代碼

使用 async 改寫指針

function promise() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
          resolve(1)
    }, 1000)
  })
}

function promise2() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
          resolve(2)
    }, 500)
  })
}

function promise3() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
          resolve(3)
    }, 500)
  })
}

async function asyncFn() {
	const step1_res = await promise()
	console.log('第一步的結果:', step1_res)
	try {
    if (step1_res === 2) {
      console.log('第二步的結果:', await promise2())
    } else {
			console.log('第二步的拒絕的結果:', await promise3())
    }
 	}
	catch(err) { 
		console.log('異常:',  err)
	}
}
asyncFn()
複製代碼

用同步的代碼寫出了異步的效果code

相關文章
相關標籤/搜索