我試圖并行地對我的數據庫對象執行一些處理(things),我使用這個包并行運行事物https://github.com/spatie/async我想知道我的事情有多少已經被成功處理,所以我$stats在全局范圍內定義了數組并嘗試從內部更新它 $pool = Pool::create(); $things = Thing::all(); $stats = [ 'total' => count($things) , 'success' => [] , ]; foreach ($things as $thing) { $pool->add(function () use ($thing , $stats ) { // do stuff return [$thing , $stats] ; })->then(function ($output ) { // Handle success list( $thing , $stats) = $output ; dump('SUCCESS'); $stats['success'][$thing->id] = $thing->id ; }) ->catch(function ($exception){ // Handle exception dump('[ERROR] -> ' . $exception->getMessage()); }); } $pool->wait(); dump($stats);即使我在輸出中看到成功,但當我轉儲時,$stats最后success總是空的array:3 [▼ "total" => 3 "success" => []]我也嘗試過,stats但then沒有use 什么區別})->then(function ($output ) use ($stats) 當我轉儲$stats到里面時then,我可以看到數據工作正常 })->then(function ($output ) { // Handle success list( $thing , $stats) = $output ; dump('SUCCESS'); $stats['success'][$thing->id] = $thing->id ; dump( $stats); })內部轉儲的輸出thenarray:3 [▼ "total" => 3 "success" => array:1 [▼ 2 => 2 ]]
1 回答

ITMISS
TA貢獻1871條經驗 獲得超8個贊
您需要做幾件事:
$stats
通過引用從父作用域繼承,在第一個回調上使用以下內容:
use ($thing, &$stats)
然后返回相同的變量作為引用:
return [$thing, &$stats];
最后,$output
在下一個回調中也通過引用取消引用相應的數組:
list($thing, &$stats) = $output; // or [$thing, &$stats] = $output;
注意:這看起來有點粗略,我不確定這是使用這個庫的正確方法,但這至少應該有效。
- 1 回答
- 0 關注
- 152 瀏覽
添加回答
舉報
0/150
提交
取消