前言
第一部分: 半协程调度器
- 统一生成器接口
- 生成器迭代
- 生成器返回值
- 生成器委托
- 改写 return
- 抽象异步模型
- 引入异常处理
- 异常: 嵌套任务透传
- 异常: 传递流程
- 异常: 重新进行 CPS 变换
- 异常: 重新加入 Async
- Syscall 与 Context
- 调度器: 里程碑
- spawn
- callcc
- race 与 timeout
- all 与 parallel
- channel 与协程间通信
- 无缓存 channel
- 缓存 channel
- channel 演示
- FutureTask 与 fork
第二部分: Koa
- 穿越地心之旅
- 洋葱圈模型
- rightReduce与中间件compose
- Koa::Application
- Koa::Context
- Koa::Request
- Koa::Response
- Koa - HelloWorld
- Middleware Interface
- Middleware: 全局异常处理
- Middleware: Router
- Middleware: 请求超时
- 一个综合示例
附录
参考
文章来源于网络收集而来,版权归原创者所有,如有侵权请及时联系!
异常: 重新进行 CPS 变换
异常: 重新进行CPS变换
我们把加入异常处理的代码重新修改为CPS方式:
<?php
final class AsyncTask
{
public $continuation;
public function begin(callable $continuation)
{
$this->continuation = $continuation;
$this->next();
}
public function next($result = null, \Exception $ex = null)
{
try {
if ($ex) {
$value = $this->gen->throw_($ex);
} else {
$value = $this->gen->send($result);
}
if ($this->gen->valid()) {
if ($value instanceof \Generator) {
// 注意这里
$continuation = [$this, "next"];
(new self($value))->begin($continuation);
} else {
$this->next($value);
}
} else {
// 迭代结束 返回结果
$cc = $this->continuation; // cc指向 父生成器next方法 或 用户传入continuation
$cc($result, null);
}
} catch (\Exception $ex) {
if ($this->gen->valid()) {
// 抛出异常
$this->next(null, $ex);
} else {
// 未捕获异常
$cc = $this->continuation; // cc指向 父生成器next方法 或 用户传入continuation
$cc(null, $ex);
}
}
}
}
<?php
function tt()
{
yield;
throw new \Exception("e");
}
function t()
{
yield tt();
yield 1;
}
$task = new AsyncTask(t());
$trace = function($r, $ex) {
if ($ex) {
echo $ex->getMessage(); // output: e
} else {
echo $r;
}
};
$task->begin($trace);
<?php
function newSubGen()
{
yield 0;
throw new \Exception("e");
yield 1;
}
function newGen()
{
try {
$r1 = (yield newSubGen());
} catch (\Exception $ex) {
echo $ex->getMessage(); // output: e
}
$r2 = (yield 2);
yield 3;
}
$task = new AsyncTask(newGen());
$trace = function($r, $ex) {
if ($ex) {
echo $ex->getMessage();
} else {
echo $r; // output: 3
}
};
$task->begin($trace); // output: e
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论