从明天开始,小编和大家一起聊一聊ES9中的新个性和新语法。这些语法和新个性在小编理论我的项目用的时候,用到的并不多,这篇之后,小编筹备把文章作为相似字典的货色,当前我的项目用到的,或者其他人写代码的时候,至多先混个脸熟。就像我前天看到的一句话一样,好代码50%是给机器运行的,另50%是给人看的,置信大家当前写的代码会越来越好,小编会和大家一起提高。大家还能够关注我的微信公众号,蜗牛全栈。
一、同步迭代器:在之前的文章中,小编更新过一篇对于es6对于可迭代协定 迭代器协定的文章,能够看看小编的这篇文章《ES6中的Module与Interator》,上面我就简略写个例子。
const arr = ["es6","es7","es8","es9"]arr[Symbol.iterator] = function(){ let nextIndex = 0 return { next(){ return nextIndex < arr.length ? { value:arr[nextIndex++], done:false }:{ value:undefined, done:true } } }}for(let item of arr){ console.log(item) // es6 es7 es8 es9}
二、异步迭代器
1、一般for...of...循环异步
function getPromise(time){ return new Promise((resolve,reject) => { setTimeout(() => { resolve(time) }) },time)}const arr = [getPromise(1000),getPromise(2000),getPromise(3000)]for(let item of arr){ console.log(item) // Promise{pending} Promise{pending} Promise{pending}}
2、异步循环:应用关键字asyncIterator
function getPromise(time){ return new Promise((resolve,reject) => { setTimeout(() => { resolve(time) }) },time)}const arr = [getPromise(1000),getPromise(2000),getPromise(3000)]for(let item of arr){ console.log(item) // Promise{pending} Promise{pending} Promise{pending}}
function getPromise(time){ return new Promise((resolve,reject) => { setTimeout(() => { resolve({ value:time, done:false }) }) },time)}const arr = [getPromise(1000),getPromise(2000),getPromise(3000)]arr[asyncIterator] = function(){ let nextIndex = 0 return { next(){ return nextIndex < arr.length ? arr[nextIndex++]:Promise.resolve({ // 相当于Promise的静态方法,返回胜利状态的Promise对象 value:undefined, done:true }) } }}for(let item of arr){ console.log(item) // Promise{pending} Promise{pending} Promise{pending}}// 等到上一次异步执行胜利之后再进行下一个异步操作async function test(){ for await (let item of arr){ console.log(item) }}test() // 1000 2000 3000