Skip to content

Commit b70c282

Browse files
author
Greg Bowler
committed
Tweak output of promise example
1 parent 1d80710 commit b70c282

2 files changed

Lines changed: 13 additions & 8 deletions

File tree

example/03-promise.php

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,8 @@ private function processNextCharacter(string $charMap):void {
5858
}
5959

6060
if($this->file->eof()) {
61+
// When the file reaches the end, this deferred task is finished. We can now
62+
// resolve the Deferred with the final value.
6163
$this->deferred->resolve($this->characterCount);
6264
return;
6365
}
@@ -88,6 +90,9 @@ private function processNextCharacter(string $charMap):void {
8890
$loop = new Loop();
8991
$loop->addTimer($timer);
9092
$loop->haltWhenAllDeferredComplete(true);
93+
$loop->addHaltCallback(function() {
94+
echo PHP_EOL, "Loop has halted because all Deferred tasks are complete.";
95+
});
9196

9297
// Create the example classes to slowly loop over the characters of the file.
9398
$reader1 = new SlowFileReader("example.txt");
@@ -101,17 +106,17 @@ private function processNextCharacter(string $charMap):void {
101106
// by the Loop's timers.
102107
$reader1->countCharacters("aeiou")
103108
->then(function(int $numVowels):void {
104-
echo "Example text has $numVowels vowels.", PHP_EOL;
109+
echo PHP_EOL, "Example text has $numVowels vowels.";
105110
});
106111

107112
// Another Promise can be added, so their Deferred's work is undertaken
108113
// concurrently.
109114
$reader2->countCharacters("bcdfghjklmnpqrstvwxyz")
110115
->then(function(int $numConsonants):void {
111-
echo "Example text has $numConsonants consonants.", PHP_EOL;
116+
echo PHP_EOL, "Example text has $numConsonants consonants.";
112117
});
113118

114119
// Here we execute the loop, which has been set to halt when all Deferred
115120
// objects complete.
116121
$loop->run();
117-
echo "Complete!", PHP_EOL;
122+
echo PHP_EOL, "Complete!", PHP_EOL;

src/Loop.php

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -84,11 +84,6 @@ public function removeDeferredFromTimer(
8484
if($activeDeferredIndex !== false) {
8585
unset($this->activeDeferred[$activeDeferredIndex]);
8686
}
87-
88-
if($this->haltWhenAllDeferredComplete
89-
&& empty($this->activeDeferred)) {
90-
$this->halt();
91-
}
9287
}
9388

9489
public function setSleepFunction(callable $sleepFunction):void {
@@ -105,6 +100,11 @@ public function run(bool $forever = true):void {
105100
do {
106101
$numTriggered = $this->triggerNextTimers();
107102
$this->triggerCount += $numTriggered;
103+
104+
if($this->haltWhenAllDeferredComplete
105+
&& empty($this->activeDeferred)) {
106+
$this->halt();
107+
}
108108
}
109109
while($numTriggered > 0 && $this->forever);
110110
}

0 commit comments

Comments
 (0)