Hack Forums
[Javascript] Favorite asynchronous pattern - Printable Version

+- Hack Forums (https://hackforums.net)
+-- Forum: Tech (https://hackforums.net/forumdisplay.php?fid=444)
+--- Forum: Coding (https://hackforums.net/forumdisplay.php?fid=151)
+---- Forum: Web Development (https://hackforums.net/forumdisplay.php?fid=183)
+---- Thread: [Javascript] Favorite asynchronous pattern (/showthread.php?tid=5702700)



Favorite asynchronous pattern - uint32 - Aug 24, 2017

They are three main asynchronous programming patterns:
  • TAP (task-based asynchronous pattern)

  • EAP (event-based asynchronous pattern)

  • CAP (callback-based asynchronous pattern)


TAP: commonly used by the form of promises or observables in javascript. Returns an object that can be queued for results. The new ES6 async/await pattern. Example:
Code
function getUser(){
    return new Promise((resolve, reject) => { ...some asynchronous stuff... resolve(result) }
}
let user = await getUser();

EAP: event is set and fired on completion. Example:
Code
let emitter = new EventEmitter();
function getUser(){
     ...some asynchronous stuff...
     emitter.emit("something", params)
}
emitter.on("something", (params) => { ...whatever... });
getUser();

CAP: callback function is passed as an argument. Example:
Code
function getUser(callback){
...some asynchronous stuff...
callback(params)
}
getUser((params) => { ...whatever... });

So, which is your personal favorite? I've heard a lot of debate over this topic, and nobody seems decided on which is best.

Personally, I prefer a TAP approach because I find it easier to understand, maintain and clean.


* - NOTHING MATTERS - Aug 25, 2017

For JS, using promises is dope, but I've noticed when using Firebase that I can't use listeners (EAP) and promises together (the promise can only be resolved once), but I can use listeners with callbacks repeatedly.

Idk if that answered your question tho lol I guess I like TAP. It depends on the use case. I use promises for getting data once, then use callbacks and listeners for getting data on changes like I said.


* - Fresku - Aug 27, 2017

Promises are nice indeed, but I like action based systems like redux aswell


* - Uncomplicated - Aug 27, 2017

+1 for TAP with async/await; makes life so much easier!


* - Faith Connors - Aug 27, 2017

I find myself doing everything web-related with EAP, but generally when not doing anything specifically for the web I default back to TAP.
Dunno, TAP seems to be my goto for like every language too haha.


* - th3s3cr3t0n3 - Aug 31, 2017

I like all three, though commonly been TAP. All three methods have their applications and uses. But syntax wise and preference would still be TAP.