Home  >  Q&A  >  body text

php - How to determine if all asynchronous callbacks have been completed in swoole?

Q1

<?php

$result = [];

(new swoole_mysql)->connect($conf, function ($db, $r) use (&$result) {
    $result[] = 1;
});

(new swoole_mysql)->connect($conf, function ($db, $r) use (&$result) {
    $result[] = 2;
});

How to judge that the above two asyncIOs have all been executed so that I can output $result?

Q2

<?php
$a = 1;
(new swoole_mysql)->connect($conf, function($db, $r) use (&a) {
    $a = 2;
});

while ($a != 2)
    continue;
    
echo $a;

Is there anything wrong with the above code? Why does echo $a never execute?

phpcn_u1582phpcn_u15822673 days ago754

reply all(1)I'll reply

  • PHPz

    PHPz2017-05-27 17:45:09

    A1:
    Since non-blocking is used, it is better to use the business logic inside the callback

    <?php
    (new swoole_mysql)->connect($conf, function ($db, $r) {
        
        //something
        (new swoole_mysql)->connect($conf, function ($db, $r) {
            //something
        });
    });
    
    

    A2:

    Since it is an asynchronous operation, the callback function may not be executed in which thread, so the context cannot be guaranteed. It is recommended to use coroutine syntax to do it.

    Summary:
    The questioner needs to understand swoole’s asynchronous model and don’t develop with synchronous thinking.

    reply
    0
  • Cancelreply