关于前端:Generatorasyncawait语法糖

18次阅读

共计 840 个字符,预计需要花费 3 分钟才能阅读完成。

Generator 生成器函数,和一般函数比就是多了个 *(星号)。调用生成器函数并不会立刻自行,而是会失去一个生成器对象,直到调用next() 办法。

function * fn(){console.log("print")
    const res = yield 'foo';
    console.log(res);
    try{...}catch(e){console.log(e);
    }
}
const generator = fn();
generator.next('para');
generator.throw(new Error('handle throw'));

函数体内能够增加 yield 关键字,他相当于暂停函数,直到执行 next() 办法。next()办法能够传入参数,它将作为 yielf 办法的返回值。
函数体外执行生成器函数的 throw() 办法则是手动抛出一个异样。让生成器外部接管。

一个 Generator 实例

function ajax(url) {...}

function* fn() {const res1 = yield ajax('...');
    console.log(res1);

    const res2 = yield ajax('...');
    console.log(res2);
}

const g = fn();
const result = g.next();
result.value.then(data => {const result2 = g.next(data);

    if (result2.done)
        return
    result2.value.then(data => {g.next(data);
    })
})

这种写法看起来会更加像同步代码,更加扁平化。调用生成器 then() 办法最好判断后果的 done 属性是否为 true。为true 时曾经完结,没必要再往下进行。

async/await 语法糖
async/await 语法糖在应用上和 generator 比更加不便,*号替换成 async,yield 替换成 await。并且async 函数会返回一个 promise 对象,更不便操作

正文完
 0