Generator 函数通过 yield 暂停执行,结合 Promise 实现异步流程控制,支持串行、并行、条件分支与错误重试,如使用 run 执行器处理 yield 返回的 Promise,实现同步式异步代码。

Generator 函数通过暂停和恢复执行的能力,为异步流程控制提供了更直观的编码方式。它与 Promise 结合使用时,可以写出类似同步代码的异步逻辑,尤其适合处理复杂的依赖、串行、并行或条件分支等场景。
Generator 函数通过 yield 暂停执行,把异步操作的结果交由外部控制机制(如自动执行器)处理。当异步任务完成,再恢复执行。
例如,实现一个自动执行器来运行基于 Promise 的 Generator:
function run(genFunc) {
const gen = genFunc();
<p>function next(val) {
const result = gen.next(val);
if (result.done) return result.value;</p><pre class='brush:php;toolbar:false;'>// 假设 yield 后面都是 Promise
result.value.then(data => next(data));}
next(); }
使用示例:
function fetchUser() {
return Promise.resolve({ id: 1, name: 'Alice' });
}
<p>function fetchPosts(userId) {
return Promise.resolve(['Post1', 'Post2']);
}</p><p>run(function* () {
const user = yield fetchUser();
console.log(user.name); // Alice
const posts = yield fetchPosts(user.id);
console.log(posts); // ['Post1', 'Post2']
});</p>利用 yield 的顺序执行特性,可轻松实现按步骤进行的复杂流程,包括条件判断和循环。
比如:
run(function* () {
const user = yield fetchUser();
<p>let items;
if (user.isAdmin) {
items = yield fetchAllData();
} else {
items = yield fetchLimitedData(user.id);
}</p><p>yield logAccess(user.id);
console.log('流程完成');
});</p>每一步都等待前一步完成,逻辑清晰,错误可通过 try-catch 捕获。
需要并发执行多个异步任务时,可以用 Promise.all 包装后 yield。
run(function* () {
const [data1, data2, data3] = yield Promise.all([
fetch('/api/a'),
fetch('/api/b'),
fetch('/api/c')
]);
console.log('全部完成:', data1, data2, data3);
});
这样既保持了代码的线性结构,又实现了并发请求,提升效率。
Generator 内部支持 try/catch,可用于捕获异步异常,并实现重试逻辑。
function retry(promiseFn, times) {
return new Promise((resolve, reject) => {
function attempt() {
promiseFn().then(resolve).catch(err => {
if (times > 1) {
times--;
setTimeout(attempt, 1000);
} else {
reject(err);
}
});
}
attempt();
});
}
<p>run(function* () {
try {
const data = yield retry(fetchCriticalData, 3);
console.log('成功获取:', data);
} catch (err) {
console.error('最终失败:', err);
}
});</p>基本上就这些。虽然现在 async/await 更常用,但理解 Generator 实现异步控制的机制,有助于深入掌握 JavaScript 的协程与执行流程管理。这种方式在需要高度定制化流程引擎的场景中仍有价值。
以上就是如何利用Generator函数实现复杂的异步流程控制?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号