What are Promises in MongoDB? - javascript

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

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

Difference between Promise.all, webdriver.promise.all, protractor.promise.all

I have a protractor test in which I use protractor.promise.all to resolve several promises and it works fine. However, if I change to use Promise.all instead of protractor.promise.all I get some error. So I think there is a significant difference between them. My questions:
1) What is the difference between:
webdriver = require('selenium-webdriver');
webdriver.promise.all
and
protractor.promise.all
and
Promise.all
2) How can I find all the cases where I have to use protractors own implementation instead of the standard. Is there a documentation about these special cases?
Thank you!
protractor.promise provides you a quick access to the webdriver promise and is the same as webdriver.promise. But Promise is a built-in EcmaScript 2015 object for asynchronous computations.
In Protractor, there is this "Control Flow" mechanism that controls the queue of webdriver promises to resolve them in order and keep thing organized. If you want for your promises to be handled with Control Flow, use webdriver promises via protractor.promise.

Can I use different promise implementations together?

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.

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.

How to think when working with promises

I'm working for the first time with async programming, specifically with promises in Javascript and I'm really confused with it. I'm still thinking like we do in C, PHP, C# and so on where for each step the next one can be sure of it's completion. This is easy to work, because if we have a code like that (in C# for example)
IEnumerable<Page> pages = pagesRepository.getAll();
we can be sure in the next line that all pages are available for us to use in the pages object. This makes life easier, because we can already do work with that data properly.
Now, in JS with promises we would have something like
var pages = dataService.getPages();
and this would not return the data, but just a promise which is very different. Of course we can add a callback with then but I'm getting confused, because somewhere else in my code I might need to reference this variable, and I cannot be sure when the callback will be called.
So how do we think when we deal with those things? Is there some tutorial or some videos out there that show in detail how to work with async programming with promises in JS?
Of course we can add a callback with then but I'm getting confused, because somewhere else in my code I might need to reference this variable, and I cannot be sure when the callback will be called.
You don't need to.
The "somewhere else code" will use .then() and yield a new promise for its result, relying on the pages promise. You can easily map the results, or chain other asynchronous tasks. Whenever you need to know about the timing of callbacks because of multiple dependencies, you should use your library's methods for composing promises, like all().
So how do we think when we deal with those things?
Think functional!
Every task in your program should explicitly and only depend on its inputs. A function should try to only use its arguments, not any global variables that contain state.
Is there some tutorial or some videos out there that show in detail how to work with async programming with promises in JS?
General Promise Resources in the wiki of the Q library is a very good start.
The simple answer here is that promises are similar to Task asynchronous programming in C#.
However instead of being able to use the 'await' operator, the 'then' function on a promise is analogous to using 'ContinueWith' to chain Tasks in C#.
Callbacks can get complicated to use across scopes, especially with extensive use of nested anonymous functions, so please give promises a go

Categories

Resources