Javascript development: When do you prefer sync over async? [closed] - javascript

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I was reading an MDN article, and it states that almost always async is a better approach than making synchronous calls from the browser to your back end. It then goes on to say "In rare cases, the use of a synchronous method is preferable to an asynchronous one." I was wondering what are some use-cases when we would prefer making synchronous requests ?

Synchronous AJAX requests completely block the UI (the same way that, for example, a native alert box does). The JavaScript concurrency model is based on leveraging asynchronous operations. I can't think of a single use-case where a synchronous request would have benefits over an async one.
As far as stylistic concerns, like "waterfalls" of callbacks, etc., these can all be managed fairly easily through different means. For example, various Promise libraries, or native ES6 features like "coroutines" (generators that deal with Promises) or even just native ES6 promises.
I think if you're running into a situation where you feel the need to call a synchronous request, then you need to step back and re-think the architecture of your application (not talking about you specifically, but just in general).

In Javascript the rule is async first! Only in case that is not possible go for synchronous !!

Related

Is await considered a bad coding practice? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I'm new to asynchronous programming and I would like to know if using await is considered a bad coding practice. I am asking this because it looks like it is possible to let the callback function do the waiting instead of letting the entire program suspend everythng until the rpocess complete.
Thank you and I appreciate your idea on this.
No, it’s not. It’s just an approach (very useful sometimes).
In modern systems complexity is so high, that in many cases having clear code is much better that having super effective code. Just an example: imagine the case when you need to make several async things one by one (maybe, fetch data based one previously fetched results). You can do it making a chain of several .then(). After that you’ll need to also add .catch(). And at this point you’ll find yourself writing spaghetti code which is a bit messy.
The other option is just make this async function with sequential calls and some logic between them. And this will look much better

Should I use ES6 on a node.js API due to performance reasons? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
Given that V8 execution of ES6 code is slower on some operations, compared to ES5.
According to this: http://incaseofstairs.com/six-speed/
Can anyone point to an article/paper/post where tests were performed in order to find out if such performance difference will impact in the normal operation of an API developed with node.js?
Should I use ES6 or greater to build a node.js API, considering it is slower to ES5?
That's a false premise right off the bat, as demonstrated by the chart you linked to.
No, this is not "premature optimization"
Yes, it is. Choice of language dialect is much more about ease of development, compatibility with libraries, and reliability. There is nothing in common implementations of ES6 that are "slower" across the board. You haven't even built your application yet, and you're worried about something that is unlikely to make a significant impact at all.
If you find that there some particular code that could be optimized, Node.js allows you to implement native binaries where you can optimize all you want.
I know some may wonder, if the API is going to get millions of hits, but again, I'm more interested in the correct pattern to use.
Use ES6.
In the back-end, we're talking about hundreds or thousands of clients, and that performance hit will be compounded.
And yet, you don't even know what the pain points are in your application because you haven't built it yet. For most applications, it's going to come down to I/O.

Asynchronous programming in JS [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I often hear something like "working knowledge of asynchronous programming" regards JavaScript in job descriptions etc, but I'm not sure what it mean - is it about callbacks and promises or is there something else to it? I'd appreciate if someone could explain this to me.
Yes, effectively. More generally, it's about understanding the asynchronous nature of the most common JavaScript environments (web browsers, Node.js) and being fully versed in using callbacks, promises, async/await (in modern environments), etc. Understanding the closures-in-loops problem, why you can't return the result from an asynchronous call, that code that looks like it's below other code in a function may run earlier than the code apparently above it (because the code above it is in a callback), etc.

should Node.js library support both promises and callbacks [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I m working on a Node.js library project that exposes asynchronous APIs to the user. I haven't worked in javascript for long, but it seems that several years ago, callbacks were used to handle asynchronous results/errors. Then promises were introduced in ES6 and async-await in ES8 (which is just more convenient way to use promises).
My question is what would a typical user of the API currently expect? I noticed an idiom in several projects where both promises and callbacks are supported, in the way that a function takes a callback as a last argument and if it is not provided, returns a Promise.
I'm wondering if this idiom should be followed in current projects or should callbacks be removed all together? Would anybody still use callbacks?
I noticed that async-await is becoming the dominant style but Node.js API itself is still callback-based (in fact the APIs usually return an event emitter, not a promise, so that user can register events on the return value).
So I'm just looking for general input from Node.js community about which direction to take.
Thanks.
Edit:
Thank you for the answers. I was asked to clarify couple of things about the project in case there are more recommendations:
(1) The API is intended to be used to access a specific product
(2) All of the calls involve network communication, basically request/response.
We definitely intend to support promises (such that each request gives user a promise that can be fulfilled or rejected), the only question is whether callbacks should still be supported as well.
Perhaps I can rephrase the questions as to be less opinion based:
1) For Node.js libraries released recently (after async-await became supported in the language) and having requirements similar to above, what is the predominant style? Could you please point me to any examples?
2) Could there be any scenario in which application would prefer handling the asynchronous result/error via callback instead of a promise?
Thanks.
A Range Of Possibilities
If your library requires a synchronous relationship with the client program then you might want to use callbacks (Programs that are I/O dependent). Otherwise, if your API has long and inconsistent response times you definitely want to be able to handle promises so you are not bottle necking applications that can't wait on every request (Routing webtraffic, etc.).
Conclusion
In my personal opinion, what makes Node.js great is the asynchronous nature of promises that let you write programs that are flexible. At the end of the day, people are going to be using your library for a diverse range of purposes and the more options you can give your users the better. Good luck!
How big is your intended user base?
If it’s small - ie contained within an easily defined group and modern tech stack, play the dictator and choose just one style.
If it’s large and has to run on many, possibly legacy platforms, consider just offering callbacks, or offer multiple flavours.

Is it possible to implement an equivalent of setTimeout() in javascript? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
Is it possible to implement a function equivalent of setTimeout() in JavaScript? If yes, what would be the best way to do that?
function setTimeout(callback, time_in_ms)
{
// Implementation of time elapse of time_in_ms
callback();
}
I am asking this question out of curiosity. A simple "No, it is not possible" would also be an enough answer to this question.
Can I implement setTimeout() in javascript myself?
No - not without some other natively asynchronous API. You might be able to implement it in terms of setInterval, with web workers, requestAnimationFrame or really anything that runs in the same event loop as setTimeout would. But if there is a reason that prevents you from using the builtin setTimeout, there probably are also other issues with your environment - so it depends on the specific situation.
A synchronous (non-asynchronous) setTimeout equivalent would be something like this:
function myTimeout(fun, milisecs) {
var nowT = Date.now();
while(Date.now()< nowT+milisecs){
continue;
}
fun();
}
function consout() {
console.log('The future arrived now!');
}
myTimeout(consout,2000);
However, as Bergi mentioned you probably want an asynchronous API to avoid stalling the JavaScript execution of your browser.
A Worker has multi-thread capabilities to allow this, with functions such as myWorker.port.start() and myWorker.terminate()... I have never needed to create something with Workers or similar APIs, but perhaps you may research a little bit more in this field (I also should not complete your homework, if that is the case).

Categories

Resources