Using a fetch promise synchronously - javascript

I need a synchronous function (it can be blocking).
I need to use Fetch, and when the promise is ready, I want to return it on the synchronous function.
Everywhere I look I can't find the answer.

I need a synchronous function
Unlikely.
(it can be blocking).
That is what synchronous means.
Long running blocking functions (including network operations) cause serious usability problems and should be avoided.
I need to use Fetch, and when the promise is ready, I want to return it on the synchronous function.
That is not possible.
XMLHttpRequest has a synchronous mode, although it is deprecated and should not be used.
You can activate it by passing false as the third parameter to open.
xhr.open("METHOD as string", "URL as strong", false);
fetch learned lessons from XMLHttpRequest and did not implement anything similar.
Learn how to deal with asynchronous code instead. The async and await keywords will let you write in in a synchronous style.

You can't block the main thread like this, the browser won't allow you(or nodejs, since I don't know which). There's no synchronous way to fetch like that. You can instead use async/await to have your code avoid callbacks. It's probably highly unadvised to do what you want to and there's a better solution, but I can't tell you much more because of lacking context.

Related

Is there any reason to prefer the async versions of functions in node.js while calling them from inside an async function?

Mainly looking at the FS api, for most functions it seems there are three flavors to choose from:
Synchronous
Asynchronous using callback
Asynchronous using promises
Async is the superior way to use system resources, however, if I'm already inside an async function and am awaiting every call anyway then there shouldn't be any difference between that and just using synchronous calls, right? To me it just seems like a built in await statement.
I don't know how async is implemented in js/node though. Is there any advantage to using async functions if I'm inside an async function to begin with? (excluding scenarios when I'm running async tasks in parallel)
One should decide to use an async function ONLY based on what is going on inside that function, not on who is calling it. The caller does not affect whether a function should be async or not.
Reasons to make a function async:
You have promise-based asynchronous operations inside the function and you wish to use await.
You have promise-based asynchronous operations inside the function and you wish to take advantage of the automatic catching of synchronous exceptions (and conversion to a rejected promise) that might occur before you invoke your asynchronous operations.
And, that's pretty much it for the reasons to use the async keyword in front of a function.
Things that an async function is NOT (or common misconceptions about async functions):
It doesn't magically make blocking code become non-blocking.
It doesn't make the caller run faster.
It doesn't make synchronous code now run in the background asynchronously.
Async is the superior way to use system resources,
Not sure what you mean there. Asynchronous functions allow you to run operations in a non-blocking fashion so that the main thread in Javascript can do other things while the asynchronous operation is running, but that is not something that an async function enables. That's enabled by an asynchronous operation. The two are different.
if I'm already inside an async function and am awaiting every call anyway then there shouldn't be any difference between that and just using synchronous calls, right?
Incorrect. Using await with a function that returns a promise does suspend execution of the current function (returning a promise immediately), but that allows the main Javascript thread to do other things, serve other requests, etc... Using synchronous code would be blocking and would not allow the main thread to do other things, thus ruining the scalability of a server.
To me it just seems like a built in await statement.
Blocking, synchronous code affects everything else that could be running during your operation. It's not the same as using await.
async/await is not equivalent to synchronous execution; it's syntactic sugar to make working with promises easier (indeed, the goal of these keywords is to make promises closer to writing synchronous code from a programming standpoint and therefore more intuitive to use).
async places a task on the event loop which will execute after all synchronous execution pending on the stack finishes. The advantages of this are clear: the process can do work while waiting for resources to be available (opening a file involves a system call, for example, so it makes sense to make this a non-blocking operation).
If you're already inside an asynchronous function, the advantages and drawbacks of asynchronous operations are just the same as they would be anywhere else. In fact, await can only be used in an async function.

How to use Synchronous XMLHttpRequest without the deprecated warning?

I wanted to use synchronous xmlhttprequest for one of my assignments and I have searched online for solution but many are related to ajax and setting the synchronous flag to true seems to resolve the problem. However I would need to set the flag to false to get my assignment done which would cause the warning. Is there a way I could use synchronous call (i.e. setting the flag to false without warning)?
Edit: I have come to the realization that firefox has completely shut down synchronous calls on the main thread. Does it mean there is no other way around it?

Prefer way of doing multiple dependent ajax synchronous call

I have seen different ways of doing multiple dependent ajax synchronous call. Two of which is being widely adopted is the jquery defer method and callback on success.
My question is:
1) What is the advantage of using one over another?
2) In what situation is one is preferred over another?
3) Is there any other better method than these 2?
// jquery defer method
var defer = $.when(
$.get('ajax_call_1');
);
defer.done(function () {
$.get('ajax_call_2');
});
// callback on success
$(function(){
$.ajax({
url:'/ajax_call_1',
data: { },
success: function(data){
$.get('ajax_call_2');
}
});
}
});
Some reasons to use Promises over Callbacks:
Much simpler to sequence multiple asynchronous operations.
Much simpler to build conditional logic involving multiple asynchronous operations.
Much simpler to do robust error handling involving multiple asynchronous operations.
Much simpler to build reusable asynchronous interfaces.
Much simpler to interface with other asynchronous interfaces.
Much simpler to deal with exceptions that might occur deep in asynchronous code that would otherwise cause silent failure
In your question, the simplest way to sequence jQuery Ajax calls and catch all possible errors is to use the natural promises returned from $.ajax() and chain them:
$.get('ajax_call_1').then(function(value) {
return $.get('ajax_call_2');
}).then(function(result) {
// success with both here
}, function(err) {
// error with one of them here
});
Or, with no error handling like in your example:
$.get('ajax_call_1').then(function(value) {
$.get('ajax_call_2');
})
There is no reason to use this construct here:
// jquery defer method
var defer = $.when(
$.get('ajax_call_1');
);
because $.get() already returns a promise so there is no need to use $.when() to just create yet another promise. $.when() is useful when you have more than one promise and you want to know when all of them are done. For one promise, you just use it directly - no reason to use $.when() with a single promise.
You can do it your second way:
// callback on success
$.ajax({
url:'/ajax_call_1',
data: { },
success: function(data){
$.get('ajax_call_2');
}
});
As this is just the non-promise way of coding with nested callbacks. The major disadvantage is that propagation of errors and sequencing multiple operations gets messy and difficult when not using promises. In just this simple example, try to get the error from either of the ajax calls back to the caller. It takes a lot of extra code to do that. My promise example above propagates all errors back to the caller for you.
As for your specific questions:
1) What is the advantage of using one over another?
You're basically asking why use promises over nested callbacks. There are hundreds of articles on the advantages of using promises. I will see if I can find one or two, but a Google search for "why promises vs. callbacks" should get you started on some reading.
What’s so great about JavaScript Promises?
Staying Sane with Asynchronous Programming
Why Am I Switching to Promises
2) In what situation is one is preferred over another?
I know of no reason why plain nested callbacks is preferred over using promises. Once you have learned promises, you will pretty much always find them a better way to code. The only reason I would not use promises is if I was trying to make code that was compatible with old browsers that did not have promises and even then, I'd probably just include a polyfill so that promises were supported.
3) Is there any other better method than these 2?
Yes, see my first code example.
P.S. Note that I choose to only use .then() with jQuery promises because that is the ES6 promise standard and it will make it easier in the future when jQuery transitions its promises to be more standards-compatible (which they are working on). Your code will also be more consistent when interfacing with other sources of promises that do use the standard.
P.P.S. Promises are one-shot devices. They either resolve or reject once and only once. If you are trying to get multiple notifications from some source, then promises are not built for that. An event emitter or a publish/subscribe system might be a better match for that type of problem.

Why is synchronous module loading in javascript that bad

I know that the synchronous ajax calls on the main thread are deprecated, but I still wonder why.
How do you archive this in asynchronous module loading: get('moduleDependency').foo(); ?
I would like to use this kind of synchronous calls at least in development to speed up the overall development circle. The modules are in production already concatenated into one file and will never touch the synchronous loading function at all.
My synchronous module loader (~80 loc) solves dependencies and more. I rewrote it to asynchronous loading, and it's working fine... but I'll have to give up using code like: get('moduleDependencie').foo();
And that's really a mess!
How do you get this kind of calls working with asynchronous loading? Or do I simply have to use asynchronous loading in cooperation with a while(true) function on the main thread in the future - until they ban while loops on the main thread also?
As long as the synchronous call isn't finished or a timeout isn't reached, there is no possibility for user to interact with the page. So it can hang up and in worst case the user has to restart his browser. Asynchronous programming and scripting is based on callbacks. You just have to bind a method to the success handler of the AJAX-Request. You can use
success:function(result){
//do something
}
or
success: myfunction
[...]
function myfunction(result){
//do something
}
Once the asynchronous code has finished, this method will be called. So put everything that works with the data from the AJAX request into this method.

Node js wrap async function

I'm implementing an API which has a function:
get(url)
Which returns a Response Object, i.e. no callback. The Http Modules I have found implements node-style async functions with callbacks. I have tried to wait for the async function to return in several ways, using Fibers etc. Fibers solves the issue within the Fiber, but can't be used in my case as I need to return the value outside any Fiber.
It might be possible to wrap the Entire Execution (including the code using the API) but I really don't want this. Is there any module that does what I want?
If I understand the question, that you're trying to mix asynchronous code with synchronous code what you're trying to accomplish is not really possible without promises. As soon as you mix asynchronous code with synchronous code, you make the entire code asynchronous, or you risk the synchronous code returning a value before the result from the synchronous code is returned.
You could always try a timeout on the function that holds it returning until a given time period has expired, which hopes that the asynchronous code executes and has a return value before the synchronous code returns. However, this is extremely inefficient, and does not eliminate the problem as you could still end up returning before the asynchronous portion has finished.
I'd also agree with the comment from robertklep that node.js really does not fit your use case, and you might be better looking at another tool for the job.

Categories