What are futures and promises

Futures and promises are constructs used in concurrent programming to handle asynchronous operations. They provide a way to retrieve values that may not be immediately available, allowing programs to continue executing while waiting for these values to be resolved.

A future represents a value that may become available at some point in the future. A promise is an object that is used to fulfill a future; once the value is available, the associated promise is completed.

Both futures and promises help manage multithreading and improve the efficiency of applications by allowing the program to proceed with other tasks while waiting for the completion of an asynchronous operation.

Here’s a simple example in PHP demonstrating the concept of futures and promises:

<?php class Promise { private $value; private $resolved = false; private $callbacks = []; public function resolve($value) { $this->value = $value; $this->resolved = true; foreach ($this->callbacks as $callback) { $callback($value); } } public function then($callback) { if ($this->resolved) { $callback($this->value); } else { $this->callbacks[] = $callback; } } } $promise = new Promise(); $promise->then(function($value) { echo "Value: $value\n"; }); $promise->resolve("Hello, world!"); ?>

futures promises asynchronous programming concurrency PHP