I wanna know whether JS promises were a part of ES5? If so, why it doesn't work sometimes in the older browsers and we have to add a polyfill for them. Also, which polyfill should be added in that case, an ES5 one or ES6? I have a little confusion regarding that.
Javascript – ES5 vs ES6 Promises
es6-promisejavascriptpromise
Related Solutions
stopPropagation
prevents further propagation of the current event in the capturing and bubbling phases.
preventDefault
prevents the default action the browser makes on that event.
Examples
preventDefault
$("#but").click(function (event) {
event.preventDefault()
})
$("#foo").click(function () {
alert("parent click event fired!")
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="foo">
<button id="but">button</button>
</div>
stopPropagation
$("#but").click(function (event) {
event.stopPropagation()
})
$("#foo").click(function () {
alert("parent click event fired!")
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="foo">
<button id="but">button</button>
</div>
With stopPropagation
, only the button
's click handler is called while the div
's click handler never fires.
Where as if you use preventDefault
, only the browser's default action is stopped but the div's click handler still fires.
Below are some docs on the DOM event properties and methods from MDN:
For IE9 and FF you can just use preventDefault & stopPropagation.
To support IE8 and lower replace stopPropagation
with cancelBubble
and replace preventDefault
with returnValue
Promises have state, they start as pending and can settle to:
- fulfilled meaning that the computation completed successfully.
- rejected meaning that the computation failed.
Promise returning functions should never throw, they should return rejections instead. Throwing from a promise returning function will force you to use both a } catch {
and a .catch
. People using promisified APIs do not expect promises to throw. If you're not sure how async APIs work in JS - please see this answer first.
1. DOM load or other one time event:
So, creating promises generally means specifying when they settle - that means when they move to the fulfilled or rejected phase to indicate the data is available (and can be accessed with .then
).
With modern promise implementations that support the Promise
constructor like native ES6 promises:
function load() {
return new Promise(function(resolve, reject) {
window.onload = resolve;
});
}
You would then use the resulting promise like so:
load().then(function() {
// Do things after onload
});
With libraries that support deferred (Let's use $q for this example here, but we'll also use jQuery later):
function load() {
var d = $q.defer();
window.onload = function() { d.resolve(); };
return d.promise;
}
Or with a jQuery like API, hooking on an event happening once:
function done() {
var d = $.Deferred();
$("#myObject").once("click",function() {
d.resolve();
});
return d.promise();
}
2. Plain callback:
These APIs are rather common since well… callbacks are common in JS. Let's look at the common case of having onSuccess
and onFail
:
function getUserData(userId, onLoad, onFail) { …
With modern promise implementations that support the Promise
constructor like native ES6 promises:
function getUserDataAsync(userId) {
return new Promise(function(resolve, reject) {
getUserData(userId, resolve, reject);
});
}
With libraries that support deferred (Let's use jQuery for this example here, but we've also used $q above):
function getUserDataAsync(userId) {
var d = $.Deferred();
getUserData(userId, function(res){ d.resolve(res); }, function(err){ d.reject(err); });
return d.promise();
}
jQuery also offers a $.Deferred(fn)
form, which has the advantage of allowing us to write an expression that emulates very closely the new Promise(fn)
form, as follows:
function getUserDataAsync(userId) {
return $.Deferred(function(dfrd) {
getUserData(userId, dfrd.resolve, dfrd.reject);
}).promise();
}
Note: Here we exploit the fact that a jQuery deferred's resolve
and reject
methods are "detachable"; ie. they are bound to the instance of a jQuery.Deferred(). Not all libs offer this feature.
3. Node style callback ("nodeback"):
Node style callbacks (nodebacks) have a particular format where the callbacks is always the last argument and its first parameter is an error. Let's first promisify one manually:
getStuff("dataParam", function(err, data) { …
To:
function getStuffAsync(param) {
return new Promise(function(resolve, reject) {
getStuff(param, function(err, data) {
if (err !== null) reject(err);
else resolve(data);
});
});
}
With deferreds you can do the following (let's use Q for this example, although Q now supports the new syntax which you should prefer):
function getStuffAsync(param) {
var d = Q.defer();
getStuff(param, function(err, data) {
if (err !== null) d.reject(err);
else d.resolve(data);
});
return d.promise;
}
In general, you should not promisify things manually too much, most promise libraries that were designed with Node in mind as well as native promises in Node 8+ have a built in method for promisifying nodebacks. For example
var getStuffAsync = Promise.promisify(getStuff); // Bluebird
var getStuffAsync = Q.denodeify(getStuff); // Q
var getStuffAsync = util.promisify(getStuff); // Native promises, node only
4. A whole library with node style callbacks:
There is no golden rule here, you promisify them one by one. However, some promise implementations allow you to do this in bulk, for example in Bluebird, converting a nodeback API to a promise API is as simple as:
Promise.promisifyAll(API);
Or with native promises in Node:
const { promisify } = require('util');
const promiseAPI = Object.entries(API).map(([key, v]) => ({key, fn: promisify(v)}))
.reduce((o, p) => Object.assign(o, {[p.key]: p.fn}), {});
Notes:
- Of course, when you are in a
.then
handler you do not need to promisify things. Returning a promise from a.then
handler will resolve or reject with that promise's value. Throwing from a.then
handler is also good practice and will reject the promise - this is the famous promise throw safety. - In an actual
onload
case, you should useaddEventListener
rather thanonX
.
Related Topic
- C# – How to trigger an event at 03:00 every night
- .Net Runtime Optimization Service Is Turning My System Unstable
- R – How to determine if an Entity with relationship properties has changes
- R – Unity framework with configuration file and singleton classes
- JavaScript Promises – reject vs. throw
- Javascript – Adding promise polyfill to ES6
- Php – wilcard DNS and Virtual subdomains
Best Answer
ES5 did not have promises. Libraries like jQuery or Angular had their own custom and non-standard promise implementations.
Popular Promise implementations for use with ES5 are Bluebird (which is compatible with the ES6 standard) and Q (which was not originally compatible with the ES6 standard- though seems to be moving that direction) and RSVP.
Neither are actual polyfills in that they don't get out of the way if native promises are present because they add additional features.
There are some pure polyfills for ES6 promises. Here's one that is a subset of RSVP: https://github.com/stefanpenner/es6-promise.
There are reasons to use more than a polyfill as you can read here: Are there still reasons to use promise libraries like Q or BlueBird now that we have ES6 promises?
Asking for a recommendation of a specific polyfill library is considered off-topic here on Stack overflow so I won't comment on that.