20. Asynchronous Operation
20.1. Backends
- Method
call_out
Method _do_call_outs
Method find_call_out
Method remove_call_out
Method call_out_info mixedcall_out(function(:void)f,float|intdelay,mixed...args)void_do_call_outs()intfind_call_out(function(:void)f)intfind_call_out(mixedid)intremove_call_out(function(:void)f)intremove_call_out(function(:void)id)array(array) call_out_info()- Description
These are aliases for the corresponding functions in
Pike.DefaultBackend.- See also
Pike.Backend()->call_out(),Pike.Backend()->_do_call_outs(),Pike.Backend()->find_call_out(),Pike.Backend()->remove_call_out(),Pike.Backend()->call_out_info()
Class Pike.Backend
- Annotations
@@Pike.Annotations.Implements(Pike.__Backend)- Description
The class of the
DefaultBackend.Typically something that has inherited
__Backend.- See also
__Backend,DefaultBackend
20.2. Promises and Futures
Module Concurrent
- Description
Module for handling multiple concurrent events.
The
FutureandPromiseAPI was inspired by https://github.com/couchdeveloper/FutureLib.
- Method
all
localvariantFutureall(array(Future)futures)localvariantFutureall(Future...futures)- Description
JavaScript Promise API equivalent of
results().- Note
The returned
Futuredoes NOT have any state (eg backend) propagated from thefutures. This must be done by hand.- See also
results(),Promise.depend()https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise
- Method
do_signal_call_callback
protectedvoiddo_signal_call_callback(function(:void)cb,mixed...args)- Description
Call the callback function
cbin a safe manner when the originatingPromisemay have been lost.- Note
Only called for failure callbacks.
If the callback fails,
global_on_failure()will be called twice; once with the error from the failing call, and once with the original error.
- Method
first_completed
variantFuturefirst_completed(array(Future)futures)variantlocalFuturefirst_completed(Future...futures)- Returns
A
Futurethat represents the first of thefuturesthat completes.- Note
The returned
Futuredoes NOT have any state (eg backend) propagated from thefutures. This must be done by hand.- See also
race(),Promise.first_completed()
- Method
fold
Futurefold(array(Future)futures,mixedinitial,function(mixed,mixed,__unknown__... :mixed)fun,mixed...extra)- Description
Return a
Futurethat represents the accumulated results of applyingfunto the results of thefuturesin turn.- Parameter
initial Initial value of the accumulator.
- Parameter
fun Function to apply. The first argument is the result of one of the
futures, the second the current accumulated value, and any further fromextra.- Note
If
funthrows an error it will fail theFuture.- Note
funmay be called in any order, and will be called once for everyFutureinfutures, unless one of calls fails in which case no further calls will be performed.- Note
The returned
Futuredoes NOT have any state (eg backend) propagated from thefutures. This must be done by hand.
- Syntax
voidon_failure(function(mixed:void)f)protectedfunction(mixed:void) Concurrent.global_on_failure- Description
Global failure callback, called when a promise without failure callback fails. This is useful to log exceptions, so they are not just silently caught and ignored.
- Method
race
variantlocalFuturerace(array(Future)futures)variantlocalFuturerace(Future...futures)- Description
JavaScript Promise API equivalent of
first_completed().- Note
The returned
Futuredoes NOT have any state (eg backend) propagated from thefutures. This must be done by hand.- See also
first_completed(),Promise.first_completed()https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise
- Method
reject
Futurereject(mixedreason)- Returns
A new
Futurethat has already failed for the specifiedreason.- Note
The returned
Futuredoes NOT have a backend set.- See also
Future.on_failure(),Promise.failure()https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise
- Method
resolve
Futureresolve(mixedvalue)- Returns
A new
Futurethat has already been fulfilled withvalueas result. Ifvalueis an object which already hason_failureandon_successmethods, return it unchanged.- Note
This function can be used to ensure values are futures.
- Note
The returned
Futuredoes NOT have a backend set.- See also
Future.on_success(),Promise.success()https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise
- Method
results
variantFutureresults(array(Future)futures)localvariantFutureresults(Future...futures)- Returns
A
Futurethat represents the array of all the completedfutures.- Note
The returned
Futuredoes NOT have any state (eg backend) propagated from thefutures. This must be done by hand.- See also
all(),Promise.depend()
- Method
serialize
Futureserialize(array(Future)futures,function(mixed,__unknown__... :mixed)fun,mixed...extra)- Description
Return a
Futurethat represents the array of mappingfunsequentially over the results of the completedfutures.This function differs from
traverse()in that only one call offunwill be active at a time. This is useful when each call offunuses lots of resources, but may increase latency.If
fun()fails for one of the items, it will not be called for any others.- Note
The returned
Futuredoes NOT have any state (eg backend) propagated from thefutures. This must be done by hand.- See also
traverse()
- Method
traverse
Futuretraverse(array(Future)futures,function(mixed,__unknown__... :mixed)fun,mixed...extra)- Description
Return a
Futurethat represents the array of mappingfunover the results of the completedfutures.- Note
The returned
Futuredoes NOT have any state (eg backend) propagated from thefutures. This must be done by hand.- See also
serialize()
- Method
use_backend
finalvoiduse_backend(intenable)- Parameter
enable 0A
falsevalue causes allConcurrentcallbacks (except for timeouts) to default to being called directly, without using a backend.1A
truevalue causes callbacks to default to being called viaPike.DefaultBackend.- Note
Be very careful about running in the backend disabled mode, as it may cause unlimited recursion and reentrancy issues.
- Note
As long as the backend hasn't started, it will default to
false. Upon startup of the backend, it will change totrueunless you explicitly calleduse_backend()before that.- Note
(Un)setting this typically alters the order in which some callbacks are called (depending on what happens in a callback).
- See also
Future()->set_backend(),Future()->call_callback()
Enum Concurrent.State
- Constant
STATE_NO_FUTURE
Constant STATE_PENDING
Constant STATE_FULFILLED
Constant STATE_REJECTED
Constant STATE_REJECTION_REPORTED constantConcurrent.STATE_NO_FUTUREconstantConcurrent.STATE_PENDINGconstantConcurrent.STATE_FULFILLEDconstantConcurrent.STATE_REJECTEDconstantConcurrent.STATE_REJECTION_REPORTED
- Constant
STATE_NO_FUTURE
Class Concurrent.AggregatedPromise (< ValueType >)
- Description
Promise to provide an aggregated
Futurevalue.Objects of this class are typically kept internal to the code that provides the
Futurevalue. The only thing that is directly returned to the user is the return value fromfuture().- Note
It is currently possible to use this class as a normal
Promise(ie without aggregation), but those functions may get removed in a future version of Pike. Functions to avoid includesuccess()andtry_success(). If you do not need aggregation usePromise.- See also
Future,future(),Promise,first_completed(),race(),results(),all(),fold()
- Generic
ValueType
__generic__mixedValueType=mixed- Description
This is the type for the value provided by the individual aggregated
Futures.
- Variable
dependency_results
protectedarray(mapping(int:ValueType)) Concurrent.AggregatedPromise.dependency_results- Description
Array mapping(int:mixed)0Successful results.
mapping(int:mixed)1Failed results.
- Method
aggregate_cb
protectedvoidaggregate_cb(mixedvalue,intidx,mapping(int:mixed)|zeroresults)- Description
Callback used to aggregate the results from dependencies.
- Parameter
value Value received from the dependency.
- Parameter
idx Identification number for the dependency.
- Parameter
results Either of the mappings in
dependency_resultsdepending on whether this was a success or a failure callback.- Note
The function may also be called with all arguments set to
UNDEFINEDin order to poll the current state. This is typically done via a call tostart().- See also
start()
- Method
any_results
this_program(<ValueType>) any_results()- Description
Sets the number of failures to be accepted in the list of futures this promise depends upon to unlimited. It is equivalent to
max_failures(-1).- Returns
The new
Promise.- See also
depend(),max_failures()
- Method
depend
this_program(<ValueType>) depend(array(Future)futures)localvariantthis_program(<ValueType>) depend(Future...futures)variantPromise(<ValueType>) depend()- Description
Add futures to the list of futures which the current object depends upon.
If called without arguments it will produce a new
Futurefrom a newPromisewhich is implictly added to the dependency list.- Parameter
futures The list of
futureswe want to add to the list we depend upon.- Returns
The new
Promise.- Note
Can be called multiple times to add more.
- Note
Once the promise has been materialised (when either
on_success(),on_failure()orget()has been called on this object), it is not possible to calldepend()anymore.- See also
fold(),first_completed(),max_failures(),min_failures(),any_results(),Concurrent.results(),Concurrent.all()
- Method
first_completed
this_program(<ValueType>) first_completed()- Description
It evaluates to the first future that completes of the list of futures it depends upon.
- Returns
The new
Promise.- See also
depend(),Concurrent.first_completed()
- Method
fold
this_program(<ValueType>) fold(mixedinitial,function(mixed,mixed,__unknown__... :mixed)fun,mixed...extra)- Parameter
initial Initial value of the accumulator.
- Parameter
fun Function to apply. The first argument is the result of one of the
futures. The second argument is the current value of the accumulator.- Parameter
extra Any extra context needed for
fun. They will be provided as arguments three and onwards whenfunis called.- Returns
The new
Promise.- Note
If
funthrows an error it will fail theFuture.- Note
funmay be called in any order, and will be called once for everyFutureit depends upon, unless one of the calls fails in which case no further calls will be performed.- See also
depend(),Concurrent.fold()
- Method
max_failures
this_program(<ValueType>) max_failures(int(-1..)max)- Parameter
max Specifies the maximum number of failures to be accepted in the list of futures this promise depends upon.
-1means unlimited.Defaults to
0.- Returns
The new
Promise.- See also
depend(),min_failures(),any_results()
- Method
min_failures
this_program(<ValueType>) min_failures(int(0..)min)- Parameter
min Specifies the minimum number of failures to be required in the list of futures this promise depends upon. Defaults to
0.- Returns
The new
Promise.- See also
depend(),max_failures()
- Method
start
protectedvoidstart()- Description
Start the aggregation of values from dependencies.
- Note
This function is called from several functions. These include
on_success(),on_failure(),wait(),get(),fold()andfirst_completed().- Note
After this function has been called, several functions may no longer be called. These include
depend(),fold(),first_completed(),max_failures(),min_failures(),any_results().
Class Concurrent.Future (< ValueType >)
- Description
Value that will be provided asynchronously sometime in the future. A Future object is typically produced from a
Promiseobject by calling itsfuture()method.- See also
Promise
- Generic
ValueType
__generic__mixedValueType=mixed- Description
This is the type for the value provided by the
Future.
- Method
apply
protectedvoidapply(mixedval,Promisep,function(mixed,__unknown__... :mixed)fun,array(mixed)ctx)- Description
Apply
funwithvalfollowed by the contents ofctx, and updatepwith the result.
- Method
apply_filter
protectedvoidapply_filter(ValueTypeval,Promisep,function(mixed,__unknown__... :bool)fun,array(mixed)ctx)- Description
Apply
funwithvalfollowed by the contents ofctx, and updatepwithvaliffundidn't return false. Iffunreturned false, failpwith0as result.
- Method
apply_flat
protectedvoidapply_flat(mixedval,Promisep,function(mixed,__unknown__... :Future)fun,array(mixed)ctx)- Description
Apply
funwithvalfollowed by the contents ofctx, and updatepwith the eventual result.
- Method
apply_smart
protectedvoidapply_smart(mixedval,Promisep,function(mixed,__unknown__... :mixed|Future)fun,array(mixed)ctx)- Description
Apply
funwithvalfollowed by the contents ofctx, and updatepwith the eventual result.
- Method
call_callback
protectedvoidcall_callback(function(:void)cb,mixed...args)- Description
Call a callback function.
- Parameter
cb Callback function to call.
- Parameter
args Arguments to call
cbwith.The default implementation calls
cbviado_call_callback()via the backend set byset_backend()(if any), and otherwise falls back to the the mode set byuse_backend().- See also
set_backend(),use_backend()
- Method
delay
this_program(<ValueType>) delay(int|floatseconds)- Description
Return a
Futurethat will be fulfilled with the fulfilled result of thisFuture, but not until at leastsecondshave passed.
- Method
do_call_callback
protectedvoiddo_call_callback(function(:void)cb,mixed...args)- Description
Call the callback function
cbin a safe manner.Reports if it fails via
global_on_failure()and updates rejection state if needed.
- Method
filter
this_programfilter(function(ValueType,__unknown__... :bool)fun,mixed...extra)- Description
This specifies a callback that is only called on success, and allows you to selectively alter the future into a failure.
- Parameter
fun Function to be called. The first argument will be the success result of this
Future. If the return value istrue, the future succeeds with the original success result. If the return value isfalse, the future fails with anUNDEFINEDresult.- Parameter
extra Any extra context needed for
fun. They will be provided as arguments two and onwards when the callback is called.- Returns
The new
Future.- See also
transform()
- Method
flat_map
localthis_programflat_map(function(ValueType,__unknown__... :this_program)fun,mixed...extra)- Description
This is an alias for
map_with().- See also
map_with()
- Method
get
ValueTypeget()- Description
Wait for fulfillment and return the value.
- Throws
Throws on rejection.
- See also
wait(),try_get()
- Method
get_backend
Pike.Backendget_backend()- Description
Get the backend (if any) used to call any callbacks.
This returns the value set by
set_backend().- See also
set_backend()
- Method
map
this_programmap(function(ValueType,__unknown__... :mixed)fun,mixed...extra)- Description
This specifies a callback that is only called on success, and allows you to alter the future.
- Parameter
fun Function to be called. The first argument will be the success result of this
Future. The return value will be the success result of the newFuture.- Parameter
extra Any extra context needed for
fun. They will be provided as arguments two and onwards when the callback is called.- Returns
The new
Future.- Note
This method is used if your
funreturns a regular value (i.e. not aFuture).- See also
map_with(),transform(),recover()
- Method
map_with
this_programmap_with(function(ValueType,__unknown__... :this_program)fun,mixed...extra)- Description
This specifies a callback that is only called on success, and allows you to alter the future.
- Parameter
fun Function to be called. The first argument will be the success result of this
Future. The return value must be aFuturethat promises the new result.- Parameter
extra Any extra context needed for
fun. They will be provided as arguments two and onwards when the callback is called.- Returns
The new
Future.- Note
This method is used if your
funreturns aFutureagain.- See also
map(),transform_with(),recover_with(),flat_map
- Method
on_await
this_program(<ValueType>) on_await(function(mixed,function(mixed,__unknown__... :void)|void:void)cb)- Description
Set both success and failure callbacks.
- Parameter
cb Callback to call with the success value on success.
On failure it is called with two arguments; the failure value and
predef::throwas the second argument.- Note
Used by
predef::await(), in which casecbwill be a generator function.- See also
on_success(),on_failure(),predef::await(),predef::throw()
- Method
on_failure
this_program(<ValueType>) on_failure(function(mixed,__unknown__... :void)cb,mixed...extra)- Description
Register a callback that is to be called on failure.
- Parameter
cb Function to be called. The first argument will be the failure result of the
Future.- Parameter
extra Any extra context needed for
cb. They will be provided as arguments two and onwards whencbis called.- Note
cbwill always be called from the main backend.- See also
on_success(),query_failure_callbacks()
- Method
on_success
this_program(<ValueType>) on_success(function(ValueType,__unknown__... :void)cb,mixed...extra)- Description
Register a callback that is to be called on fulfillment.
- Parameter
cb Function to be called. The first argument will be the result of the
Future.- Parameter
extra Any extra context needed for
cb. They will be provided as arguments two and onwards whencbis called.- Note
cbwill always be called from the main backend.- See also
on_failure(),query_success_callbacks()
- Method
promise_factory
Promise(<ValueType>) promise_factory()- Description
Create a new
Promisewith the same base settings as the current object.Overload this function if you need to propagate more state to new
Promiseobjects.The default implementation copies the backend setting set with
set_backend()to the newPromise.- See also
Promise,set_backend()
- Method
query_failure_callbacks
array(function(mixed,__unknown__... :void)) query_failure_callbacks()- Description
Query the set of active failure callbacks.
- Returns
Returns an array with callback functions.
- See also
on_failure(),query_success_callbacks()
- Method
query_success_callbacks
array(function(ValueType,__unknown__... :void)) query_success_callbacks()- Description
Query the set of active success callbacks.
- Returns
Returns an array with callback functions.
- See also
on_success(),query_failure_callbacks()
- Method
recover
this_programrecover(function(mixed,__unknown__... :mixed)fun,mixed...extra)- Description
This specifies a callback that is only called on failure, and allows you to alter the future into a success.
- Parameter
fun Function to be called. The first argument will be the failure result of this
Future. The return value will be the success result of the newFuture.- Parameter
extra Any extra context needed for
fun. They will be provided as arguments two and onwards when the callback is called.- Returns
The new
Future.- Note
This method is used if your callbacks return a regular value (i.e. not a
Future).- See also
recover_with(),map(),transform()
- Method
recover_with
this_programrecover_with(function(mixed,__unknown__... :this_program)fun,mixed...extra)- Description
This specifies a callback that is only called on failure, and allows you to alter the future into a success.
- Parameter
fun Function to be called. The first argument will be the failure result of this
Future. The return value must be aFuturethat promises the new success result.- Parameter
extra Any extra context needed for
fun. They will be provided as arguments two and onwards when the callback is called.- Returns
The new
Future.- Note
This method is used if your callbacks return a
Futureagain.- See also
recover(),map_with(),transform_with()
- Method
set_backend
voidset_backend(Pike.Backendbackend)- Description
Set the backend to use for calling any callbacks.
- Note
This overides the mode set by
use_backend().- See also
get_backend(),use_backend()
- Method
signal_call_callback
protectedvoidsignal_call_callback(function(:void)cb,mixed...args)- Description
Call a callback function from a signal handler.
- Parameter
cb Callback function to call.
- Parameter
args Arguments to call
cbwith.- Note
The default implementation calls
cbviado_signal_call_callback()viapredef::call_out()(ie the backend set byset_backend()is intentionally NOT used).- See also
set_backend(),call_callback()
- Method
then
this_programthen(void|function(ValueType,__unknown__... :mixed)onfulfilled,void|function(mixed,__unknown__... :mixed)onrejected,mixed...extra)- Description
JavaScript Promise API close but not identical equivalent of a combined
transform()andtransform_with().- Parameter
onfulfilled Function to be called on fulfillment. The first argument will be the result of this
Future. The return value will be the result of the newFuture. If the return value already is aFuture, pass it as-is.- Parameter
onrejected Function to be called on failure. The first argument will be the failure result of this
Future. The return value will be the failure result of the newFuture. If the return value already is aFuture, pass it as-is.- Parameter
extra Any extra context needed for
onfulfilledandonrejected. They will be provided as arguments two and onwards when the callbacks are called.- Returns
The new
Future.- See also
transform(),transform_with(),thencatch(),on_success(),Promise.success(),on_failure(),Promise.failure(), https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise
- Method
thencatch
localthis_programthencatch(function(mixed,__unknown__... :mixed)onrejected,mixed...extra)- Description
JavaScript Promise API equivalent of a combination of
recover()andrecover_with().- Parameter
onrejected Function to be called. The first argument will be the failure result of this
Future. The return value will the failure result of the newFuture. If the return value already is aFuture, pass it as-is.- Parameter
extra Any extra context needed for
onrejected. They will be provided as arguments two and onwards when the callback is called.- Returns
The new
Future.- See also
recover(),recover_with(),then(),on_failure(),Promise.failure(), https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise
- Method
timeout
this_program(<ValueType>) timeout(int|floatseconds)- Description
Return a
Futurethat will either be fulfilled with the fulfilled result of thisFuture, or be failed aftersecondshave expired.
- Method
transform
this_programtransform(function(ValueType,__unknown__... :mixed)success,function(mixed,__unknown__... :mixed)|voidfailure,mixed...extra)- Description
This specifies callbacks that allow you to alter the future.
- Parameter
success Function to be called. The first argument will be the success result of this
Future. The return value will be the success result of the newFuture.- Parameter
failure Function to be called. The first argument will be the failure result of this
Future. The return value will be the success result of the newFuture. If this callback is omitted, it will default to the same callback assuccess.- Parameter
extra Any extra context needed for
successandfailure. They will be provided as arguments two and onwards when the callbacks are called.- Returns
The new
Future.- Note
This method is used if your callbacks return a regular value (i.e. not a
Future).- See also
transform_with(),map(),recover()
- Method
transform_with
this_programtransform_with(function(ValueType,__unknown__... :this_program)success,function(mixed,__unknown__... :this_program)|voidfailure,mixed...extra)- Description
This specifies callbacks that allow you to alter the future.
- Parameter
success Function to be called. The first argument will be the success result of this
Future. The return value must be aFuturethat promises the new result.- Parameter
failure Function to be called. The first argument will be the failure result of this
Future. The return value must be aFuturethat promises the new success result. If this callback is omitted, it will default to the same callback assuccess.- Parameter
extra Any extra context needed for
successandfailure. They will be provided as arguments two and onwards when the callbacks are called.- Returns
The new
Future.- Note
This method is used if your callbacks return a
Futureagain.- See also
transform(),map_with(),recover_with
- Method
try_get
ValueType|zerotry_get()- Description
Return the value if available.
- Returns
Returns
UNDEFINEDif theFutureis not yet fulfilled.- Throws
Throws on rejection.
- See also
wait()
- Method
wait
this_program(<ValueType>) wait()- Description
Wait for fulfillment.
- See also
get(),try_get()
- Method
zip
this_programzip(array(this_program)others)localvariantthis_programzip(this_program...others)- Parameter
others The other futures (results) you want to append.
- Returns
A new
Futurethat will be fulfilled with an array of the fulfilled result of this object followed by the fulfilled results of other futures.- See also
results()
Class Concurrent.Promise (< ValueType >)
- Description
Promise to provide a
Futurevalue.Objects of this class are typically kept internal to the code that provides the
Futurevalue. The only thing that is directly returned to the user is the return value fromfuture().- See also
Future,future()
- Generic
ValueType
__generic__mixedValueType=mixed- Description
This is the type for the value provided by the inherited
Future.
- Method
create
Concurrent.PromiseConcurrent.Promise(void|function(function(ValueType:void),function(mixed:void),__unknown__... :void)executor,mixed...extra)- Description
Creates a new promise, optionally initialised from a traditional callback driven method via
executor(success, failure, @extra).- See also
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise
- Method
failure
this_program(<ValueType>) failure(mixedvalue)- Description
Reject the
Futurevalue.- Parameter
value Failure result of the
Future.- Throws
Throws an error if the
Futurealready has been fulfilled or failed.Mark the
Futureas failed, and schedule theon_failure()callbacks to be called as soon as possible.- See also
try_failure(),success(),on_failure()
- Method
success
this_program(<ValueType>) success(ValueTypevalue)- Description
Fulfill the
Future.- Parameter
value Result of the
Future.- Throws
Throws an error if the
Futurealready has been fulfilled or failed.Mark the
Futureas fulfilled, and schedule theon_success()callbacks to be called as soon as possible.- See also
try_success(),try_failure(),failure(),on_success()
- Method
try_failure
localthis_program(<ValueType>) try_failure(mixedvalue)- Description
Maybe reject the
Futurevalue.- Parameter
value Failure result of the
Future.Mark the
Futureas failed if it hasn't already been fulfilled, and in that case schedule theon_failure()callbacks to be called as soon as possible.- See also
failure(),success(),on_failure()
- Method
try_success
localthis_program(<ValueType>) try_success(ValueType|zerovalue)- Description
Fulfill the
Futureif it hasn't been fulfilled or failed already.- Parameter
value Result of the
Future.Mark the
Futureas fulfilled if it hasn't already been fulfilled or failed, and in that case schedule theon_success()callbacks to be called as soon as possible.- See also
success(),try_failure(),failure(),on_success()