迭代器
function makeIteeator(arr) {
let nextIndex = 0;
//返回一个迭代器对象
return {
next: () => {
//next()方法返回的对象结果
if (nextIndex < arr.length) {
return {
value: arr[nextIndex++],
done: true
}
} else {
return { done: true }
}
}
}
}
const it = makeIteeator(['吃饭', '睡觉', '打豆豆'])
console.log('首先', it.next().value)
console.log('其次', it.next().value)
console.log('然后', it.next().value)
console.log('最后', it.next().value)
生成器函数
function* makeIterator(arr) {
for (let i = 0; i < arr.length; i++) {
yield arr[i]
}
}
const gen = makeIterator(['吃饭', '睡觉', '打豆豆'])
console.log('首先', gen.next().value)
console.log('其次', gen.next().value)
console.log('然后', gen.next().value)
console.log('最后', gen.next().done)
co库(源码)
const co = require('co');
const fetch = require('node-fetch');
co(function*() {
const res = yield fetch('https://api.douban.com/v2/movie/1291843')
const movie = yield res.json()
const summary = movie.summary
console.log('summary', summary)
})
//上面的执行过程
function run(generator) {
const iterator = generator()
const it = iterator.next()
const promise = it.value
promise.then(data => {
const it2 = iterator.next(data)
const promise2 = it2.value
promise2.then(data2 => {
iterator.next(data2)
})
})
}
箭头函数
写法精简
和定义父作用域共享this
用法示例
const arrow = function(param){}
const arrow = (param)=>{}
const arrow=param=>{}
const arrow =param=>console.log(param)
const arrow = param=({param:param})
const arrow = (param1,param2)=>{}
const arrow=({id,movie})=>{
console.log(id,movie)
}
处理异步的场景
const fs = require('fs')
//第一阶段回调函数
function readFile(cb) {
fs.readFile('./package.json', (err, data) => {
if (err) return console.log(err)
data = JSON.parse(data)
cb(null, data)
})
}
readFile((err, data) => {
if (!err) {
data.JSON.parse(data)
console.log(data.name)
}
})
//第二阶段promise
function readFileAsync(path) {
return new Promise((resolve, reject) => {
fs.readFile(path, (err, data) => {
if (err) reject(err)
else resolve(data)
})
})
}
readFileAsync('./package.json')
.then(data => {
data = JSON.parse(data)
console.log(data.name)
})
//第三阶段
const co = require('co');
const util = require('util')
co(function*() {
let data = yield util.promisify(fs.readFile)('./package.json')
data = JSON.parse(data)
console.log(data.name)
})
//第四阶段Async统一事件
const readAsync = util.promisify(fs.readFile)
async function init() {
let data = await readAsync('./package.json')
data = JSON.parse(data)
console.log(data.name)
}
init()