Skip to content

4. Async in order

Exanlv edited this page Mar 3, 2024 · 4 revisions

Sometimes you may need to execute several async actions in order. This can be accomplished using (among others) a recursive anonymous function.

This example shows how to send several messages in order, you can also abstract this further to an array of anonymous functions returning a promise, which you can then use everywhere.

use Ragnarok\Fenrir\Rest\Helpers\Channel\MessageBuilder;

$sendMessages = function (string $channelId, array $items) use (&$sendMessages, $discord) {
    if (count($items) === 0) {
        return;
    }

    $messageToSend = array_shift($items);

    $discord->rest->channel->createMessage(
        $channelId,
        (new MessageBuilder())->setContent($messageToSend)
    )->then(fn () => $sendMessages($channelId, $items));
};

$sendMessages($message->channel_id, ['this', 'will', 'send', 'in', 'order']);

Clone this wiki locally