An example of each, using javascript since everybody can read it.
Please don’t use this code in production, use a real library, there are plenty of good ones.
var a, b, c, async_obj; // assume exist
// CommonJS - for reference purposes
try {
async_obj.asyncMethod(a, b, c, function (error1, result1) {
if (error1) {
console.error(error1);
} else {
console.log(result1);
}
});
} catch (ex1) {
console.error(ex1);
}
// Thunk - "a parameterless closure created to prevent the evaluation of an expression until forced at a later time"
function makeThunkForAsyncMethod (cb) {
return function () {
async_obj.asyncMethod(a, b, c, cb);
}
}
var my_thunk = makeThunkForAsyncMethod(function (error1, result1) {
if (error1) {
console.error(error1);
} else {
console.log(result1);
}
});
setTimeout(function () {
try {
my_thunk();
} catch (ex1) {
console.error(ex1);
}
}, 5e3);
// Promise - "a writable, single assignment container which sets the value of the future"
function makePromiseForAsyncMethod () {
var
future_then_cb,
future_catch_cb,
future
;
future = {
then: function (cb) {
future_then_cb = cb;
},
catch: function (cb) {
future_catch_cb = cb;
};
};
try {
async_obj.asyncMethod(a, b, c, function (error1, result1) {
if (error1) {
if (future_catch_cb) {
future_catch_cb(error1)
}
} else {
if (future_then_cb) {
future_then_cb(result1);
}
}
});
} catch (ex1) {
setTimeout(function () {
if (future_catch_cb) {
future_catch_cb(ex1);
}
});
}
return future;
}
// Future - "a read-only placeholder view of a variable"
var my_future = makePromiseForAsyncMethod();
my_future
.then(function (result) {
console.log(result);
})
.catch(function (error) {
console.error(error);
})
;
A Promise chain would be like the above contrived example, but it would work on collections and be more robust.