\Co\defer
###API
namespace Co;
function defer(Closure $closure): string;
Parameter descriptionβ
Parameters | Type | Description |
---|---|---|
$closure | Closure | Delayed execution of the closure function, running in the event context |
Closure parametersβ
none
Return valueβ
Returns the unique identifier of the current event, allowing the event to be canceled using the \Co\cancel
method
Overviewβ
Defer (delayed execution), executes a closure function immediately after the current event ends, usually used for resource release and other operations.
Basic usageβ
\Co\async(function () {
$file = fopen('file.txt', 'w');
\Co\defer(function () use ($file) {
//TODO: The code here will not be executed immediately
fclose($file);
});
fwrite($file, 'hello world');
return 'async task';
});
defer is useful in actual scenarios, such as releasing resources after an asynchronous request ends.
public function index(Request $request) : JsonResponse
{
\Co\defer(function() use ($request){
$response = \Co\await(
\Co\Net::HTTP()->Guzzle()->getAsync('http://example.com');
);
$channel = \Co\IO::Channel()->open('websocket');
$channel->send($response->getBody()->getContent());
$channel->close();
});
return new JsonResponse(['status' => 'ok']);
}
hintβ
In the scaffolding provided by ripple, most framework controller requests will occur in the async space. You can use the
\Co\defer
method in the controller.