DOM promises for browsers and node.js
DOM Promises for browsers and node.js. Acts like a polyfill in browsers without support for DOM Promises, and NPM package for node.js applications.
DOM Promises is a quiet new spec introduced by WhatWG. Promises provide a convenient way to get access to the result of an operation. You can use this package either in browser (it acts like a polyfill if your browser is missing support for DOM Promises) or in your node.js code. This feature used to be called futures.
npm install dom-futures
returnvar xhr = ;xhropen"GET" url true;xhrresponseType = "json";if xhrresponseresolverresolvexhrresponse;elseresolverreject"JSONError";;xhronerror =resolverrejectevttype;;xhrsend;;// okay, now check this:fetchJSON"/user/posts"thenshowPosts showFailcat;
As you can see, you can create chains with promises by passing a fulfillCallback function which returns a new Promise. If your fulfillCallback returns some value, the promise will be resolved with it. Check this:
fetchJSON"/users"thenvar firstUserId = jsonusers0id;return fetchJSON"/users/" + firstUserId;thenvar userCommentsUrl = jsoncommentsurl;return fetchJSON"/comments/" + userCommentsUrl;then// and so on...;
DOM Promises also have a bunch of helpers, or so-called "static methods".
Returns a promise that is fulfilled or rejected when all values are fulfilled or any is rejected. You should pass promises to this function.
// browser examplereturnvar xhr = ;xhrwithCredentials = true;xhropen"GET" url true;resolverresolveevttargetresponseText;;resolverrejectevttype;;xhrsend;;PromiseeveryloadResource"" loadResource""then// htmlContents is 2-elements array// handle err;// node.js examplevar Promise = require"dom-futures"Promise;var fs = require"fs";returnfsreadFilepath "utf-8"if errresolverrejecterr;elseresolverresolvecontents;;;PromiseeveryreadFile"/etc/hosts" readFile"/etc/group" readFile"/etc/shadow"then// filesContents is 3-elements array// handle err;
Returns a promise that is fulfilled or rejected when one of values is fulfilled or all are rejected. You should pass promises to this function.
Returns a promise that is fulfilled or rejected when any of values is either fulfilled or rejected. You should pass promises to this function.
Returns a promise that is fulfilled with result value. This is the easiest way to create a new fulfilled Promise with "value" as a promise result and "fulfilled" as a promise state.
Returns a promise that depends upon value. In fact this kind of static method allows you to create a promises chain from the beginning. If you pass a promise object, the state of returned promise will be set as "pending" and result will be undefined. But if you pass smth other than promise, this will act like you call
Returns a promise that is rejected with result value.