函数中间件、promisify实现

187 阅读1分钟

一、函数中间件实现

1、通过生成器函数返回一个迭代器;

2、nextDo函数的接受迭代器执行next函数返回值obj对象,value就是要执行的函数;

3、如果obj.done的值取反值为true,执行test1函数,test1函数的参数是一个函数,test1里面的next执行的就是该函数"参数函数"。

4、参数函数执行迭代器下一次迭代,返回的值通过递归调用nextDo函数。

5、直到每一个函数都执行完成,或者被执行函数不执行next,也意味着参数函数不被执行,那么递归结束。

var funs = [];
funs.push(function test1(next) {
	console.log('test1');
	next()
})
funs.push(function test2(next) {
	console.log('test2');
	next()
})
funs.push(function tes3t(next) {
	console.log('test3');
	next()
})
funs.push(function test4(next) {
	console.log('test4');
	next()
});
// funs = [];
var m = function(fns) {
	let iterator;
	function init() {
		iterator = generator(fns)
		nextDo(iterator.next())
	}
	function* generator(fns) {
		for (let obj of fns) {
			yield obj
		}
	}
	function nextDo(obj) {
		if (!obj.done) {
			obj.value(function() {
				let nextObj = iterator.next()
				nextDo(nextObj)
			})
		}
	}
	return {
		init
	}
}
m(funs).init()

二、promisify实现同步读取文件

let fs = require('fs'),
	readFile = promisify(fs.readFile);
readFile('./city.txt', 'utf-8')
	.then(res => readFile('./company.txt', 'utf-8'))
	.then(res => console.log(res))

function promisify(func) {
	return function(...arg) {
		return new Promise((resovle, reject) => {
			func(...arg, (err, data) => {
				if (err) {
					reject(err);
				} else {
					resovle(data)
				}
			})
		})

	}
}