node - co中的thunkify该怎么写

查看:132
本文介绍了node - co中的thunkify该怎么写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

c

这样写node报错,这个thunkify包装该怎么写?

解决方案

示例如下:

const co = require('co')
const thunkify = require('thunkify')
const fs = require('fs')

// 在此 thunkify 原函数,得到一个【输入参数为回调函数】的函数
const read = thunkify(fs.readFile)

function * wrapper () {
  // yield 语句对函数或 Promise 生效,对原始值不生效
  let x = yield read('demo.js', 'utf8')
  return x
}

// co 自动执行 wrapper 生成器,在 Promise 中获取 yield 结果
co(wrapper).then(data => {
  console.log(data)
})

这篇关于node - co中的thunkify该怎么写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆