我試圖并行地對(duì)我的數(shù)據(jù)庫(kù)對(duì)象執(zhí)行一些處理(things),我使用這個(gè)包并行運(yùn)行事物https://github.com/spatie/async我想知道我的事情有多少已經(jīng)被成功處理,所以我$stats在全局范圍內(nèi)定義了數(shù)組并嘗試從內(nèi)部更新它 $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);即使我在輸出中看到成功,但當(dāng)我轉(zhuǎn)儲(chǔ)時(shí),$stats最后success總是空的array:3 [▼ "total" => 3 "success" => []]我也嘗試過,stats但then沒有use 什么區(qū)別})->then(function ($output ) use ($stats) 當(dāng)我轉(zhuǎn)儲(chǔ)$stats到里面時(shí)then,我可以看到數(shù)據(jù)工作正常 })->then(function ($output ) { // Handle success list( $thing , $stats) = $output ; dump('SUCCESS'); $stats['success'][$thing->id] = $thing->id ; dump( $stats); })內(nèi)部轉(zhuǎn)儲(chǔ)的輸出thenarray:3 [▼ "total" => 3 "success" => array:1 [▼ 2 => 2 ]]
1 回答

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