- Generator生成器函数:
function * foo () {
console.log('start')
try {
const res = yield 'foo' // 使用yield关键字向外返回一个值 暂停generator函数的执行
console.log(res)
}catch (e){
console.log(e)
}
}
let generator = foo()
const result = generator.next()
generator.next('bar') // 作为yield这个语句的返回值
generator.throw('err')
// generator + Promise
function ajax (url) {
return new Promise(function (resolve, reject) {
let xhr = new XMLHttpRequest()
xhr.open('GET', url)
xhr.responseType = 'json'
xhr.onload = function () {
if (this.status + '' === '200') {
resolve(this.response)
console.log(this.response)
} else {
reject(new Error(this.responseText))
console.log(this.responseText)
}
}
xhr.send()
})
}
function * main () {
const users = yield ajax('/ajaxTest.js')
const post = yield ajax('/ajaxPost.js')
}
let g = main()
const result = g.next()
if (result.done) return
result.then(data => {
const result1 = g.next(data)
if (resul1.done) return
result1.value.then(res => {
g.next(res)
})
})