Tasks can be executed asynchronously only if NO dependency.
With dependency, there will be a producer and a consumer. Consumer need to process result provided by producer. There are several ways to achieve this from history.
- callbacks : producer is defined with a function on what to do after
- Promise : producer returns an object with what to do after
- async/await :
- producer logic defined with a callback for consumer to hook in
- consumer logic defined in callback and passed to producer
# producer
function producer( args, callback ) {
try {
result = take_time_to_get_result()
callback(null, result)
} catch (err) {
callback(err)
}
}
# consumer
function consumer(producer) {
producer(args, function(err, result) {
if (err) {
handle_error(err)
} else {
consume(result)
}
})
}
- producer logic is encapsulated in Promise and executed upon creation
- consumer logic is defined and passed to Promise object, not as callback to producer
- consumers can be added in dynamically
# producer
function producer(args) {
function executor(resolve, reject) {
try {
value = take_time_to_get_result()
resolve(value)
} catch (err) {
reject(err)
}
}
return new Promise( executor );
};
# consumer
function consumer() {
let promise = producer(args)
promise.then(result_handler(result), error_handler(error));
}
state | result |
---|---|
pending | undefined |
fulfilled | value |
rejected | error |
async
function always returns a promiseawait
(must insideasync
function) makes the script wait until promise settles and returns