如何解决吞噬池:重构匿名函数后如何获得池响应
例如,我想重构以下代码:
更易读(没有匿名功能)。喜欢
$fulfilled = New Fulfilled($phones);
$rejected = New Rejected();
$pool = new Pool(...,[
'concurrency' => 15,'fulfilled' => $Fulfilled,'rejected' => $Rejected,]);
我创建了一个满足这样的课程
但是我如何找回我的&$ result?
食堂是一个难题。
[编辑] 正如从Abiux所说的那样,一个类不是那么易读。我试图像这样在$ pool外部提取匿名函数
public function fulfilled($response,$index){
$body=$response->getBody();
$status=$response->getStatusCode();
$reason=$response->getReasonPhrase();
$result[] = [
"userNumber" => $this->phones[$index],"status" => $status,"reason" => $reason,"body" => json_decode($body,true)];
return $result;
}
// -------------------------------------
public function get_async($phones){
...
$client = new Client();
$requests = function ($phones) use ($filter){
foreach ($phones as $phone){
$url="contexts?userNumber=$phone&$filter";
yield new Request('GET',$url);
}
};
$rejected = new Rejected();
$pool = new Pool($client,$requests($phones),[
'concurrency' => 2,'options' => $options,'fulfilled' => ['this','fulfilled',&$result],'rejected' => $rejected,]);
// Initiate the transfers and create a promise
$promise = $pool->promise();
// Force the pool of requests to complete.
$promise->wait();
return $result;
}
但它也失败
解决方法
首先,不要将匿名函数替换为类。它不是更易读,也没有任何目的(据您的解释)。
第二,您可以将$result
作为对象实例化的一部分传递给__construct()
,然后在__invoke
函数中引用它。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。