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

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.

Related

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

return deferred or deferred.promise() [duplicate]

What are the differences between Deferreds, Promises and Futures?
Is there a generally approved theory behind all these three?
These answers, including the selected answer, are good for introducing promises
conceptually, but lacking in specifics of what exactly the differences are in
the terminology that arises when using libraries implementing them (and there
are important differences).
Since it is still an evolving spec, the answer currently comes from attempting to survey both references (like wikipedia) and implementations (like jQuery):
Deferred: Never described in popular references,
1
2
3
4
but commonly used by implementations as the arbiter of promise resolution (implementing resolve and reject).
5
6
7
Sometimes deferreds are also promises (implementing then),
5
6
other times it's seen as more pure to have the Deferred only
capable of resolution, and forcing the user to access the promise for
using then.
7
Promise: The most all-encompasing word for the strategy under discussion.
A proxy object storing the result of a target function whose
synchronicity we would like to abstract, plus exposing a then function
accepting another target function and returning a new promise.
2
Example from CommonJS:
> asyncComputeTheAnswerToEverything()
.then(addTwo)
.then(printResult);
44
Always described in popular references, although never specified as to
whose responsibility resolution falls to.
1
2
3
4
Always present in popular implementations, and never given
resolution abilites.
5
6
7
Future: a seemingly deprecated term found in some popular references
1
and at least one popular implementation,
8
but seemingly being phased out of discussion in preference for the term
'promise'
3
and not always mentioned in popular introductions to the topic.
9
However, at least one library uses the term generically for abstracting
synchronicity and error handling, while not providing then functionality.
10
It's unclear if avoiding the term 'promise' was intentional, but probably a
good choice since promises are built around 'thenables.'
2
References
Wikipedia on Promises & Futures
Promises/A+ spec
DOM Standard on Promises
DOM Standard Promises Spec WIP
DOJO Toolkit Deferreds
jQuery Deferreds
Q
FutureJS
Functional Javascript section on Promises
Futures in AngularJS Integration Testing
Misc potentially confusing things
Difference between Promises/A and Promises/A+
(TL;DR, Promises/A+ mostly resolves ambiguities in Promises/A)
In light of apparent dislike for how I've attempted to answer the OP's question. The literal answer is, a promise is something shared w/ other objects, while a deferred should be kept private. Primarily, a deferred (which generally extends Promise) can resolve itself, while a promise might not be able to do so.
If you're interested in the minutiae, then examine Promises/A+.
So far as I'm aware, the overarching purpose is to improve clarity and loosen coupling through a standardized interface. See suggested reading from #jfriend00:
Rather than directly passing callbacks to functions, something which
can lead to tightly coupled interfaces, using promises allows one to
separate concerns for code that is synchronous or asynchronous.
Personally, I've found deferred especially useful when dealing with e.g. templates that are populated by asynchronous requests, loading scripts that have networks of dependencies, and providing user feedback to form data in a non-blocking manner.
Indeed, compare the pure callback form of doing something after loading CodeMirror in JS mode asynchronously (apologies, I've not used jQuery in a while):
/* assume getScript has signature like: function (path, callback, context)
and listens to onload && onreadystatechange */
$(function () {
getScript('path/to/CodeMirror', getJSMode);
// onreadystate is not reliable for callback args.
function getJSMode() {
getScript('path/to/CodeMirror/mode/javascript/javascript.js',
ourAwesomeScript);
};
function ourAwesomeScript() {
console.log("CodeMirror is awesome, but I'm too impatient.");
};
});
To the promises formulated version (again, apologies, I'm not up to date on jQuery):
/* Assume getScript returns a promise object */
$(function () {
$.when(
getScript('path/to/CodeMirror'),
getScript('path/to/CodeMirror/mode/javascript/javascript.js')
).then(function () {
console.log("CodeMirror is awesome, but I'm too impatient.");
});
});
Apologies for the semi-pseudo code, but I hope it makes the core idea somewhat clear. Basically, by returning a standardized promise, you can pass the promise around, thus allowing for more clear grouping.
What really made it all click for me was this presentation by Domenic Denicola.
In a github gist, he gave the description I like most, it's very concise:
The point of promises is to give us back functional composition and error bubbling in the async world.
In other word, promises are a way that lets us write asynchronous code that is almost as easy to write as if it was synchronous.
Consider this example, with promises:
getTweetsFor("domenic") // promise-returning async function
.then(function (tweets) {
var shortUrls = parseTweetsForUrls(tweets);
var mostRecentShortUrl = shortUrls[0];
return expandUrlUsingTwitterApi(mostRecentShortUrl); // promise-returning async function
})
.then(doHttpRequest) // promise-returning async function
.then(
function (responseBody) {
console.log("Most recent link text:", responseBody);
},
function (error) {
console.error("Error with the twitterverse:", error);
}
);
It works as if you were writing this synchronous code:
try {
var tweets = getTweetsFor("domenic"); // blocking
var shortUrls = parseTweetsForUrls(tweets);
var mostRecentShortUrl = shortUrls[0];
var responseBody = doHttpRequest(expandUrlUsingTwitterApi(mostRecentShortUrl)); // blocking x 2
console.log("Most recent link text:", responseBody);
} catch (error) {
console.error("Error with the twitterverse: ", error);
}
(If this still sounds complicated, watch that presentation!)
Regarding Deferred, it's a way to .resolve() or .reject() promises. In the Promises/B spec, it is called .defer(). In jQuery, it's $.Deferred().
Please note that, as far as I know, the Promise implementation in jQuery is broken (see that gist), at least as of jQuery 1.8.2.
It supposedly implements Promises/A thenables, but you don't get the correct error handling you should, in the sense that the whole "async try/catch" functionality won't work.
Which is a pity, because having a "try/catch" with async code is utterly cool.
If you are going to use Promises (you should try them out with your own code!), use Kris Kowal's Q. The jQuery version is just some callback aggregator for writing cleaner jQuery code, but misses the point.
Regarding Future, I have no idea, I haven't seen that in any API.
Edit: Domenic Denicola's youtube talk on Promises from #Farm's comment below.
A quote from Michael Jackson (yes, Michael Jackson) from the video:
I want you to burn this phrase in your mind:
A promise is an asynchronous value.
This is an excellent description: a promise is like a variable from the future - a first-class reference to something that, at some point, will exist (or happen).
A Promise represents a proxy for a value not necessarily known when the promise is created. It allows you to associate handlers to an asynchronous action's eventual success value or failure reason. This lets asynchronous methods return values like synchronous methods: instead of the final value, the asynchronous method returns a promise of having a value at some point in the future.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
The deferred.promise() method allows an asynchronous function to prevent other code from interfering with the progress or status of its internal request. The Promise exposes only the Deferred methods needed to attach additional handlers or determine the state (then, done, fail, always, pipe, progress, state and promise), but not ones that change the state (resolve, reject, notify, resolveWith, rejectWith, and notifyWith).
If target is provided, deferred.promise() will attach the methods onto it and then return this object rather than create a new one. This can be useful to attach the Promise behavior to an object that already exists.
If you are creating a Deferred, keep a reference to the Deferred so that it can be resolved or rejected at some point. Return only the Promise object via deferred.promise() so other code can register callbacks or inspect the current state.
Simply we can say that a Promise represents a value that is not yet known where as a Deferred represents work that is not yet finished.
A promise represents a value that is not yet known
A deferred represents work that is not yet finished
A promise is a placeholder for a result which is initially unknown while a deferred represents the computation that results in the value.
Reference
http://blog.mediumequalsmessage.com/promise-deferred-objects-in-javascript-pt1-theory-and-semantics

Do protractor's expects wait internally for promises?

I came across this answer in a SO question:
'AFAIK expect waits internally for the related promises.'
Does anyone know if this is correct? I've searched the protractor documentation for an answer with no luck. Can anyone point out the correct place in the documentation where it say this?
If it is correct, it would save me a lot of work! We have over two hundred tests, and to prevent timeouts I am converting all these types of calls:
expect(parentDialog.getAttribute('class')).toContain('k-window-maximized');
to this:
parentDialog.getAttribute('class').then(function(cls) {
expect(cls).toContain('k-window-maximized');
});
This is definitely true. expect() is "patched" by jasminewd/jasminewd2 (used by protractor internally) to implicitly resolve promises. Quote from the README:
Enhances expect so that it automatically unwraps promises before
performing the assertion.
Here is an another documentation reference:
The WebDriver Control Flow > Protractor Adaptations
In other words, unless you need a real resolved value for further actions or calculations, you can safely pass a promise into expect():
expect(parentDialog.getAttribute('class')).toContain('k-window-maximized');

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.

Differences in using Q vs When promise library for javascript [duplicate]

What aspects of a promise library does the spec not cover? What kind of things vary between implementations?
Please illustrate with examples of actual differences (eg between Bluebird and Q).
Almost everything. The Promises/A+ spec is aimed for promise interoperability, it's built so promise libraries (and now, native promises) can talk to each other. The idea is for it to be possible to predict how a promise behaves and to define how promises are assimilated by other libraries.
Quoting the specification:
This specification details the behavior of the then method, providing an interoperable base which all Promises/A+ conformant promise implementations can be depended on to provide. As such, the specification should be considered very stable. Although the Promises/A+ organization may occasionally revise this specification with minor backward-compatible changes to address newly-discovered corner cases, we will integrate large or backward-incompatible only after careful consideration, discussion, and testing. Finally, the core Promises/A+ specification does not deal with how to create, fulfill, or reject promises, choosing instead to focus on providing an interoperable then method. Future work in companion specifications may touch on these subjects.
The following are not covered:
Creating a promise (that's the promise constructor spec).
Promise aggregation (although most implementations support .all).
Progression (that's the progression spec, which will soon be replaced imo).
Cancellation (that's the cancellation spec).
Unhandled rejection monitoring (there is no spec, but there is an inspection discussion).
Stack traces.
Bluebird and Q for example, are both completely Promises/A+ complaint but differ on a lot of these:
The next Q, v2 introduces estimation, where Bluebird intends to deprecate progression eventually in favor of something like C#'s IProgress.
Creating a promise is usually done with deferreds in Q (although it now offers a promise constructor variant), Bluebird encourages the promise constructor.
Bluebird has more robust and stronger promisification abilities, turning a whole callback API to promises in a single command. Q author Kris built Q-IO which manually promisifies the filesystem and http modules.
Bluebird allows scoped binding of this value via .bind, and promise array methods (.map,.reduce,.filter etc).
Q has primitives like asynchronous queues, and RPC via Q-connection in mind,
Bluebird is about 100 times faster, has better stack traces, and automatic unhandled rejection detection. It also consumes a lot less RAM memory per promise.
Here is another reference

Categories

Resources