Can I use different promise implementations together? - javascript

I've written a script to deploy a web project. It fist uploads a bunch of files via FTP and then sends a request to a chat bot posting a message to https://chat.stackexchange.com/.
I'm new to JavaScript and Node.js, and didn't know about promises when I first wrote the code. I'm now in the process of converting it from using nested callbacks to promises with the Node build-in Promise.
For making the HTTP request to the bot I've been using request. There's another library called request-promise using Bluebird promises. Are these compatible with the built-in promise implementation? Are there any gotchas I have to look out for?
There's a site listing Conformant Promise/A+ Implementations, but neither Node.js nor Chromium is listed there. Does this mean that I can't use them together?

You will have to trust the claim that Request-promise is a drop-in replacement for Request
bluebird is a superset of the current built in Promise implementation in node. That is to say that you can use them interchangeably except that bluebird has more features/methods. Rather than try to mix them I would just use bluebird everywhere.
If you really don't want to, though, it shouldn't make any difference in terms of chaining promises together. The following still logs hello as expected.
let bluebird = require("bluebird");
new bluebird(resolver => resolver())
.then(() => new Promise(resolver => resolver()))
.then(() => console.log("hello"));
Using Promise = require("bluebird") is pretty common as well.

They are compatible. Probably some implementations differ a little bit, but the main Promise flow is the same. Bluebird seems to be faster even than the native Node.JS implementation.

Related

When to use 'async' built-in for ES2017 or import 'npm i async'

I recently learned that async/await is built into ES2017, but I have made several projects that I needed to require the package async in order to use async/await.
Is there an easy way to tell when I can access async normally or when I need to import it? Do I ever need to use that npm package? What is the purpose of the async package (which currently shows 47,469,002 weekly downloads) if the exact same functionality is now built into the language?
For an example project that requires async feel free to look at the Local-Library MongoDB/Express/Node tutorial project on MDN.
Since this is an Express app (as several of my own are), does this have anything to do with ExpressJS?
I have looked around for about a bit trying to find these answers but have come up empty-handed. Any help understanding this is appreciated.
The async library on NPM provides a number of utility functions for managing asynchronous operations. That is very different than the async keyword in the language that allows you to use await with promises. These are like cats and dogs. They both have something to do with asynchronous programming, but other than that, they really aren't the same thing at all.
For example, suppose you need to make 1000 separate requests to a particular host, but for a variety of reasons (memory consumption, rate limiting by the host, etc...), you cannot have more than 5 requests to target host in flight at any given time. So, you want to launch 5 requests and then each time one finishes, you'll launch another one until you've finally done all 1000.
The async keyword in ES7 could perhaps be used in some custom code to implement the algorithm above I described, but by itself, it doesn't give you that solution.
Whereas the async library from NPM has a specific function in its toolkit for doing exactly what I described. It's called parallelLimit() and it lets you specify exactly how many operations you want to be in parallel at a time (with no more than that). In fact, the async library contains all sorts of utility functions for managing asynchronous control flow and you can see a whole list of them here: https://caolan.github.io/async/v3/docs.html#parallelLimit.
Now that we have the async keyword in the language, some of those algorithms are no longer needed because it's very easy to code them in plain ES7. For example if you want to iterate over an array one at a time, calling an asynchronous function on each item, you can just use a for loop and await, all inside an async function.
async function run() {
for (let x of myArray) {
await doSomeAsyncOperation(x);
}
}
Before we had async and await in ES7, you would have had to either write a bit of custom code to do this asynchronous, serialized iteration or you would use a pre-built function from a library such as the async library.
Summary
To review, the async library contains a number of utility functions for managing asynchronous operations. Some of those are no longer necessary because of the control flow options that async and await provide in ES7 and some are still helpful/useful even with the presence of async and await.
FYI, the async library was originally developed before we even had promises and async/await in Javascript and it dealt with the older-style asynchronous operations that used plain callbacks to signal completion or error and offered utilities for managing them. Promises and async/await have replaced the need for some of the functionality in the async library, but not all.
When to use 'async' built-in for ES2017 or import 'npm i async'
Use the built-in ES7 async/await when it directly and simply solves the asynchronous control flow problem you need to solve. Use a function from the async library when you can't easily solve your problem with just async/await and the async library contains a pre-built function that solves your problem directly and simply.
So, the async library is just one of hundreds of thousands of libraries on NPM. You use it when it contains something that helps you solve your job better than what is already built-into the language, the same logic for when to use any other module from NPM.
aysnc/await that are part of ES2017 enables cleaner style there by avoiding promise chains. See the below example mentioned in mdn. You avoid promise chains like then, catch and yet have asynchronous behaviour
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function
Async library that you mentioned is more of a utility( they mainly designed to use with node js), It takes the array of callbacks, executes and wraps the them and gives you a promise. Iy also enables you with lot more features like in case you want invoking callback in parallel, serial, chain the callbacks, there by helping track these with a common success/error handling

What are Promises in MongoDB?

I am currently working on a project with mongoDB and am receiving this notification in the terminal:
"DeprecationWarning: Mongoose: mpromise (mongoose's default promise library) is deprecated, plug in your own promise library instead: http://mongoosejs.com/docs/promises.html"
I am fairly new to mongo and have no idea what these "promises" are. I also checked out the link in the notification, but still cannot understand what it is saying.
If someone could please explain what "promises" are within mongodb and what I should do about this deprecation, that would be great. Thanks!
Promises in MongoDB are just like promises in the larger JS ecosystem. They are an alternative to callback functions which allow for step-by-step orderly execution of asynchronous code.
As your Mongo link, shows, for example, you can use Promise.then() instead of a callback function.
Here is some further discussion.
Here are some other promise implementations:
Bluebird
jQuery
Native ES6/ES2015+ Promises

Not wanting promises to swallow errors

I'm switching some code from bluebird to native Promises and am getting rather annoyed at the fact that native promises swallow errors even when there's not a .catch() defined. It makes debugging impossible unless you put a catch() on every promise.
So my question -- Does anyone have a solution to this? Possibilities include some way to tell promises to throw, or a way to globally catch them, or...?
I wrote and Petka (bluebird's author) implemented (we had help :)) this functionality for Node a little back. I don't think you should switch from bluebird (it's faster and has a richer API) but if you want - use the rejection hooks:
process.on('unhandledRejection', function(p, reason) {
// handle error here, all "swallowed" errors get here
});
This requires io.js 1.4+ or modern NodeJS (3.0+), this won't work in node 0.12, so better use a modern version or just keep using bluebird (which is also compatible with this event)

How to retrieve native function code after it was redefined by third-party js?

I'm writing a userscript for tumblr that makes ajax calls to its API over an array of data and I need the responses to come in the order the data was in the array. I was advised to use Promises for that as the article shows (http://www.html5rocks.com/en/tutorials/es6/promises/#toc-parallelism-sequencing).
It works on individual tumblr blog pages, but not on the dashboard, where native implementation of Promise is overwritten by their index.js. As the result, their Promise lacks .resolve() ability and my code doesn't work.
Can I still find a way to use the native Promise or do I have to seek other ways? I'd prefer to stick with Promises to avoid having different code for a single use case. Alternatively, I would have to use jQuery for same functionality and I don't really know how.
Right now I'm solving this by force-loading of Promise polyfill from GitHub, but this doesn't feel right.

Why does NodeJS NOT use Promise for the readFile API?

In the book https://pragprog.com/book/tbajs/async-javascript, I found this:
Node’s early iterations used Promises in its nonblocking API. However,
in February 2010, Ryan Dahl made the decision to switch to the
now-familiar callback(err, results...) format, on the grounds that
Promises are a higher-level construct that belongs in “userland.”
It looks quite confusing to me, because as an API to read files, this
fs.readFile('/etc/passwd')
.onSuccess(function(data){console.log(data)})
.onError(function(err){throw err})
looks much better than this:
fs.readFile('/etc/passwd', function (err, data) {
if (err) throw err;
console.log(data);
});
Does anyone have ideas about why "Promises are a higher-level construct" will stops itself from being used in NodeJS API?
Node v8 ships with util.promisify that converts callback APIs to promises, Node v10 ships with native promises support (experimental):
const fs = require('fs').promises;
// in an async function:
let data = await fs.readFile('/etc/passwd');
console.log(data);
The future is promises:
NodeJS will use promises for the new APIs. In fact it is currently discussed how. An earlier attempt in 0.2 to use Promises in node years ago failed because of friction and performance issues.
What has to happen first:
Now promises are a native language feature, but the following has to happen before they make it to the core APIs:
Promises have to be a native language construct this already happened.
The NodeJS and io.js merger that was recently announced has to happen - the time frame is a few short months probably.
The v8 (JavaScript engine) team has to finish working on private symbols which will enable fast promise creation. At the moment the promise constructor is the only way to create promises in native promises and it allocates a closure which is relatively expensive. This is currently being done with Domenic working in tight coordination between the io.js and v8 team to ensure this is done properly.
The v8 team has to optimize the promise implementation, currently native promises lose consistently to userland implementations like bluebird. This is also happening now.
Once all these happen the API will be forked and a version containing promises will be integrated into core. Here is a long and uninteresting discussion about it - there is a better one at the io.js/NG repo but neither are really too informative.
What can be done today
Libraries like bluebird give you tools to instantly convert a callback API to promises in a fast and efficient way. You can use them today and get that functionality.
Historically callbacks are the default for performance reasons, but...
Update 2017 / Node 8: Promises are now supported by the core!
Node.js supports promises since Node v8.x. The APIs are all still written in callback style (for backwards compatibility etc.), but there now is a utility class in node core to convert the callback-based APIs to promise-based APIs (similarly to bluebird):
https://nodejs.org/api/util.html#util_util_promisify_original
From the Node.js docs:
For example:
const util = require('util');
const fs = require('fs');
const stat = util.promisify(fs.stat);
stat('.').then((stats) => {
// Do something with `stats`
}).catch((error) => {
// Handle the error.
});
Or, equivalently using async functions:
const util = require('util');
const fs = require('fs');
const stat = util.promisify(fs.stat);
async function callStat() {
const stats = await stat('.');
console.log(`This directory is owned by ${stats.uid}`);
}
Update 2018 / Node 10: New fs.promises API
The fs.promises API provides an alternative set of asynchronous file system methods that return Promise objects rather than using callbacks. The API is accessible via require('fs').promises.
https://nodejs.org/api/fs.html#fs_fs_promises_api
(experimental at this moment, but working perfectly on node latest)
Promises is a library, when using promise it requires to return Promise constructor from function but using callback function chaining same thing is achievable that's why "Promises are a higher-level construct"
Reference: Promises in node js

Categories

Resources