一路繁花似锦绣前程
失败的越多,成功才越有价值

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
统计
 

二十七、知识点回顾

1、回调函数方式处理异步所存在的问题
* 无法捕获错误(try catch)
* 不能return
2、生成器
function* foo(a) {
  const b = yield a
  const c = yield b
  return c
}

const iter = foo(1)
console.log(iter.next())
console.log(iter.next(2))
console.log(iter.next(3))
/*
// 伪代码
function foo(a) {
  // 相当于从:foo(a) 执行到 yield a
  // 可通过foo()传入参数
  function 第一个next() {
    return { value: a, done: false }
  }
  // 相当于从:const b 执行到 yield b
  // 可通过第二个next()传入参数
  function 第二个next(b) {
    return { value: b, done: false }
  }
  // 相当于从:const c 执行到 return c
  // 可通过第三个next()传入参数
  function 第三个next(c) {
    return { value: c, done: true }
  }
}
*/
3、从Generator到async/await
// co.wrap原理
function wrap(gen) {
  return function (...args) {
    const it = gen(...args)
    return new Promise(resolve => {
      (function next(res) {
        const {value, done} = it.next(res)
        if (done) {
          resolve(value)
        } else {
          Promise.resolve(value).then(next)
        }
      })()
    })
  }
}

// 需要安装:npm i co
// const {wrap} = require('co')
const foo = wrap(function* (a) {
  const b = yield Promise.resolve(a + 1)
  const c = yield Promise.resolve(b + 1)
  return c + 1
})
/*
// 相当于
const foo = async function (a) {
  const b = await Promise.resolve(a + 1)
  const c = await Promise.resolve(b + 1)
  return c + 1
}
*/

foo(1).then(res => {
  console.log(res)
})
posted on   一路繁花似锦绣前程  阅读(12)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~
历史上的今天:
2020-03-27 springboot整合测试_springboot整合log4j
2020-03-27 SpringBootApplication注解_RestController注解
 
点击右上角即可分享
微信分享提示