Promise.all vs Axios.all - javascript

I would like to ask the difference between "Promise.all" & "Axios.all" for several API requests.
I found that both work well in my code, but it is not easy to find its reason..
Could you please explain ?

The Axios documentation on NPM says that Axios.all() is deprecated and you should use Promise.all() in its place. I do not believe there is any intended difference between the two.
In fact, if you look in the current Axios source, you see this:
// Expose all/spread
axios.all = function all(promises) {
return Promise.all(promises);
};
So, they are identical.
I presume that Axios.all() existed historically when Axios wanted to be able to run in environments that didn't have full native promise support so they were supplying promise functionality that might now be present.
Since all modern environments contain Promise.all(), Axios.all() is no longer necessary.

Related

MongoDb inbuilt Promises

How to know what all methods in mongoDb has an inbuilt promise in it.
eg: "updateOne() , findOne()" these methods have inbuilt promises and and we can access the response using ".then" but for lots of other mongoDB methods lack this feature how can we be sure of which methods dont have inbuilt promise in them?
eg: "find()" has no inbuilt promise so we cannott perform "find().then((response)=>{})" this will give an error.
Whereas "findOne().then((response)=>{})" will work without any issue.
This is inconsistent across the NodeJS MongoDB driver as some methods return more complex objects for manipulating the returned values. For example, .find() returns a FindCursor object which can be used to iterate over results by calling .next() repeatedly.
I would recommend referring the MongoDB documentation for the NodeJS driver (found here, or common usage examples are here) rather frequently. The documentation is reasonably extensive and should help with issues like this.
You can also consider using TypeScript, which I have personally found helpful for cases such as this because you can easily tell what type of object is returned from a function/method call.
I would recommend referring the MongoDB documentation for the NodeJS driver (found here, or common usage examples are here) rather frequently. The documentation is reasonably extensive and should help with issues like this
There is some inconsistency over the find method in MongoDB native driver in node Js. This is because the reason that the finds method returns a cursor. So what we could do here is convert that to an array using the toArray() method.
The best solution here would be to use async await over promise chaining.
This would provide us with a cleaner and easier syntax to work with.
Eg :
Let's say we want to find all the products in the product collection. Below is a function for doing exactly that.
const findAll=async(userId)=>{
const userData= await db.products.find().toArray();
console.log(userData);
return userData;
}
Upon calling the above function we would get all the products in the product collection. Just by looking at the code, we could see that it provides a more readable syntax than chaining promises all over.

google apps script with UrlfetchApp.fetchAll() or with async/ await for multiple http requests?

I created some projects in Google Apps Script in the past for some automation, that also included some http-fetches. In the past, this worked with .fetch() pretty well, but now we need to fetch multiple urls.
Since apps script now uses V8 runtime I considered to do so with promises. I'm also quite new to async/await and promises in general.
So I considered to try the UrlfetchApp.fetch() within async functions, just to find out, that there's no difference in execution time.
I red, that UrlfetchApp.fetch() will always be sync, no matter whether you declare your function as async or not, due to the GAS-API-design. But I can't find detailed infos on this.
Is this true?
If yes: Then the only way to fetch multiple urls would be UrlfetchApp.fetchAll(), right?
If no: Means simple .fetch() would work inside async funcs (and could be chained in Promise.all()) then I'd invest further time in this.
So, yes or no would help a lot here!
Currently, Urlfetchapp runs synchronously and although the syntax of promises are supported, it works synchronously too.
Then the only way to fetch multiple urls would be UrlfetchApp.fetchAll(), right?
Yes

Static/dynamic way to detect dangling promises

I know this problem has been dealt with so many times, but none of them seem to solve the issue of reliably detecting dangling promises (even those that resolve properly).
So I want to be able to figure out a way (whether at runtime or better at static time) to root out "dangling promises", especially of this class:
async function a() {
... do some async operation ...
}
async function b() {
a(); // forgot to call await on it
}
where I have accidentally forget to await on one function and some task that executes asynchronously doesn't get awaited on. Often times these types of bugs don't throw exceptions so I can't just use "unhandledRejection" and call it a day.
At this point after lots of desperate attempts I just need a way to detect this kinda faulty pattern at either (optimally) static/compile/lint time or at runtime. Runtime for me I think should work assuming I have good test coverage.
tl;dr basically, I'm searching for some code that would do something like the following:
Error: Potential dangling promise detected!
...
at b (/dangling.js:5:3)
For each dangling promise
My thought process
I first tried finding some static analysis library that would help to detect these things (theoretically it should be possible but I had no luck with finding such a thing). A while back I remember finding something in the depths of stackoverflow that talked about using some typescript checker to check for dangling promises, though now I can't find it anymore :( . Though at the time changing the entire codebase to typescript was a no-go. (Later I learned you can actually use tsc to typecheck javascript (given that you do some type annotation in comments))
Currently I was previously using node version 11, so I thought about using the node.js's async_hooks API and try to listen on events (apparently simply monkey patching the Promise constructor wouldn't work because node.js bypasses the Promise constructor when creating a Promise object to return from an async function). Using node v11, after a bit of code hackery here it seemed to work (though it's not very efficient cause it throws away a lot of promise optimization in the v8 engine, but it does the job). There was a small hiccup in this entire operation in that I had to still monkey patch the then/catch/finally functions of the Promise API to check if we are currently calling that function (somehow that worked with detecting some dangling promises).
Now enter node v12 (apparently I need this for certain other things that are breaking), and now that hackery (unsurprisingly) completely breaks. After scrutinizing the version diffs, seems like they optimized the await/async implementation. After narrowing down the reason, it seems like await no longer calls the then function of the promise and just directly does some native shenanigans (idk what really).
Now I'm actually kinda desperate for some solution (and maybe if Typescript has some way of type-checking these dangling promises, what was the option to enable this check? I know (tested) that tsc doesn't do this by default).
You are most likely looking for the no-floating-promises rule of typescript-eslint

RxJS + (async/await) for (multiple-event) use cases

I am writing a Javascript App to get data from sensors. I started using ES6 Promises + Generators using Bluebird and the Bluebird.cororutine in both (client and server), but it didn't work fine.
I was advised that Promises didn't work properly in (multiple-event) use cases, and that an alternative could be RxJS.
I've taken a look to RxJS, and it looks like can do the same as the Promises but even better.
I wanted to use generators (async/await) to write the async code to look as sync, and my question is:
Can I use RxJS + (async/await) or RxJS has already its own way to do the same as (async/await) ?
Thanks
Async/await is not part of ES6, it's scheduled for ES7. So you're probably not going to use it any time soon in JavaScript. TypeScript supports async/await for ES5 since 2.1.
It think you'll be able to use RxJS with async/await when it comes out. Async/await works with Promises, just like RxJS even though it mostly works with Observables. There are methods such as Observable.toPromise() to convert an Observables to Promises and most Observables also accept a Promise as a parameter.
So I think both are going to be well interchangable (I haven't tried thi personally).
If your primary interest is to make you code more readable than RxJS is a good choice to reduce callback hell.
These two examples show how to call multiple HTTP requests in order using Observable.concatMap() operator. Both examples are written in TypeScript but it should be basically the same in
ES6 as well. Also these examples use the new RxJS implementation (https://github.com/ReactiveX/RxJS):
Angular 2 + rxjs - how return stream of objects fetched with several subsequent http requests
How to use exhaustMap in ReactiveX/rxjs 5 in TypeScript

How do I debug promise-based code in node?

I am using Cujo's great When library to provide a Promises/A+ implementation for my Node project, although this question is not node-specific.
Generally, When's great: it lets me write more maintainable, readable code.
However, when my callbacks fail unexpectedly (accessing a property of a null variable, etc), the exceptions are effectively swallowed by When, as seems to be specified by the Promises/A+ spec. Unfortunately, this means I don't get any feedback about the error (other than the callback stops executing at that point). No error type or message, no line number.
To illustrate:
// hypothetical asynchronous database query
database.query(queryDetails).then(function(result) {
var silly = 3.141592654;
silly(); // TypeError: number is not a function!
process(result); // this code is silently never executed
});
I can think of a handful of (unacceptable) ways to tackle this:
providing failure callbacks for every then call (to dump the reason/exception to the console)
wrapping all callback bodies in try-catches
littering the codebase with "landmark logs" ala console.log('I got here 123')
Am I just doing it wrong? Surely I'm not alone in finding the debuggability of promises-based code poor. Is there an obvious solution I'm missing?
Update Sep 2016: NodeJS 6.6.0+ and 7.0+ will warn automatically on unhandled rejections. Run node with --trace-warnings to get reasonable stack traces. Still not as good as what bluebird gives you but a lot better than the situation before.
Ok, so summing up the information from the comments and add some.
There is nothing in the Promises/A+ specification that dictates how to deal with this problem. The specification is about the minimal requirements for good interop between different promise libraries - so one promise library can consume promises created in another and vice versa.
Several libraries solve this problem by including a .done method that explicitly declares the chain has ended, this causes uncaught rejections to be thrown. Libraries like When and Q solve the problem this way. For example if your .then after .query was a .done you'd get a long stack trace.
Newer, less naive implementations of promises like Bluebird solve this problem by automatically figuring out possibly uncaught rejections and logging them out for you loudly. They also give you a hook. When has experimental support for this using the monitor.
As such:
require('when/monitor/console'); // when will now log async rejections used with
// `then` , this is experimental in when.
With bluebird
Promise.longStackTraces(); // Bluebird always logs async rejections but with this
// option it will stitch the asynchronous context stack
// for you in your methods.
ES6 promises' behavior is unspecified on this. There is no explicit requirements on the native implementations with regards to this. However, I know vendors are working on it and I'd expect engines to start figuring this out even in native implementations.
Here is how I detect when a Promise has been rejected on Node but not caught:
if (typeof process === 'object') {
process.on('unhandledRejection', (error, promise) => {
console.error("== Node detected an unhandled rejection! ==");
console.error(error.stack);
});
}
In addition to that, you could use this monkey wrapper to provide long stack traces for Node's ES6 Promises. It produces similar output to Q's longStackSupport. I would not recommend it for use outside of development code, due to performance concerns. (It's working for me in Node v4.4.1. I have not yet tested it in Chrome or Firefox.)

Categories