source: frontend/node_modules/promise/Readme.md

Last change on this file was 9af201e, checked in by MBK <marija.karapandzova@…>, 11 days ago

Fix frontend appearance

  • Property mode set to 100644
File size: 11.3 KB
Line 
1<a href="https://promisesaplus.com/"><img src="https://promisesaplus.com/assets/logo-small.png" align="right" /></a>
2# promise
3
4This is a simple implementation of Promises. It is a super set of ES6 Promises designed to have readable, performant code and to provide just the extensions that are absolutely necessary for using promises today.
5
6For detailed tutorials on its use, see www.promisejs.org
7
8**N.B.** This promise exposes internals via underscore (`_`) prefixed properties. If you use these, your code will break with each new release.
9
10[![Build Status](https://img.shields.io/github/workflow/status/then/promise/Publish%20Canary/master?style=for-the-badge)](https://github.com/then/promise/actions?query=workflow%3APublish%20Canary+branch%3Amaster)
11[![Rolling Versions](https://img.shields.io/badge/Rolling%20Versions-Enabled-brightgreen?style=for-the-badge)](https://rollingversions.com/then/promise)
12[![NPM version](https://img.shields.io/npm/v/promise?style=for-the-badge)](https://www.npmjs.com/package/promise)
13[![Downloads](https://img.shields.io/npm/dm/promise.svg?style=for-the-badge)](https://www.npmjs.org/package/promise)
14
15## Installation
16
17**Server:**
18
19 $ npm install promise
20
21**Client:**
22
23You can use browserify on the client, or use the pre-compiled script that acts as a polyfill.
24
25```html
26<script src="https://www.promisejs.org/polyfills/promise-6.1.0.js"></script>
27```
28
29Note that the [es5-shim](https://github.com/es-shims/es5-shim) must be loaded before this library to support browsers pre IE9.
30
31```html
32<script src="https://cdnjs.cloudflare.com/ajax/libs/es5-shim/3.4.0/es5-shim.min.js"></script>
33```
34
35## Usage
36
37The example below shows how you can load the promise library (in a way that works on both client and server using node or browserify). It then demonstrates creating a promise from scratch. You simply call `new Promise(fn)`. There is a complete specification for what is returned by this method in [Promises/A+](http://promises-aplus.github.com/promises-spec/).
38
39```javascript
40var Promise = require('promise');
41
42var promise = new Promise(function (resolve, reject) {
43 get('http://www.google.com', function (err, res) {
44 if (err) reject(err);
45 else resolve(res);
46 });
47});
48```
49
50If you need [domains](https://nodejs.org/api/domain.html) support, you should instead use:
51
52```js
53var Promise = require('promise/domains');
54```
55
56If you are in an environment that implements `setImmediate` and don't want the optimisations provided by asap, you can use:
57
58```js
59var Promise = require('promise/setimmediate');
60```
61
62If you only want part of the features, e.g. just a pure ES6 polyfill:
63
64```js
65var Promise = require('promise/lib/es6-extensions');
66// or require('promise/domains/es6-extensions');
67// or require('promise/setimmediate/es6-extensions');
68```
69
70## Unhandled Rejections
71
72By default, promises silence any unhandled rejections.
73
74You can enable logging of unhandled ReferenceErrors and TypeErrors via:
75
76```js
77require('promise/lib/rejection-tracking').enable();
78```
79
80Due to the performance cost, you should only do this during development.
81
82You can enable logging of all unhandled rejections if you need to debug an exception you think is being swallowed by promises:
83
84```js
85require('promise/lib/rejection-tracking').enable(
86 {allRejections: true}
87);
88```
89
90Due to the high probability of false positives, I only recommend using this when debugging specific issues that you think may be being swallowed. For the preferred debugging method, see `Promise#done(onFulfilled, onRejected)`.
91
92`rejection-tracking.enable(options)` takes the following options:
93
94 - allRejections (`boolean`) - track all exceptions, not just reference errors and type errors. Note that this has a high probability of resulting in false positives if your code loads data optimistically
95 - whitelist (`Array<ErrorConstructor>`) - this defaults to `[ReferenceError, TypeError]` but you can override it with your own list of error constructors to track.
96 - `onUnhandled(id, error)` and `onHandled(id, error)` - you can use these to provide your own customised display for errors. Note that if possible you should indicate that the error was a false positive if `onHandled` is called. `onHandled` is only called if `onUnhandled` has already been called.
97
98To reduce the chance of false-positives there is a delay of up to 2 seconds before errors are logged. This means that if you attach an error handler within 2 seconds, it won't be logged as a false positive. ReferenceErrors and TypeErrors are only subject to a 100ms delay due to the higher likelihood that the error is due to programmer error.
99
100## API
101
102Detailed API reference docs are available at https://www.promisejs.org/api/.
103
104Before all examples, you will need:
105
106```js
107var Promise = require('promise');
108```
109
110### new Promise(resolver)
111
112This creates and returns a new promise. `resolver` must be a function. The `resolver` function is passed two arguments:
113
114 1. `resolve` should be called with a single argument. If it is called with a non-promise value then the promise is fulfilled with that value. If it is called with a promise (A) then the returned promise takes on the state of that new promise (A).
115 2. `reject` should be called with a single argument. The returned promise will be rejected with that argument.
116
117### Static Functions
118
119 These methods are invoked by calling `Promise.methodName`.
120
121#### Promise.resolve(value)
122
123(deprecated aliases: `Promise.from(value)`, `Promise.cast(value)`)
124
125Converts values and foreign promises into Promises/A+ promises. If you pass it a value then it returns a Promise for that value. If you pass it something that is close to a promise (such as a jQuery attempt at a promise) it returns a Promise that takes on the state of `value` (rejected or fulfilled).
126
127#### Promise.reject(value)
128
129Returns a rejected promise with the given value.
130
131#### Promise.all(array)
132
133Returns a promise for an array. If it is called with a single argument that `Array.isArray` then this returns a promise for a copy of that array with any promises replaced by their fulfilled values. e.g.
134
135```js
136Promise.all([Promise.resolve('a'), 'b', Promise.resolve('c')])
137 .then(function (res) {
138 assert(res[0] === 'a')
139 assert(res[1] === 'b')
140 assert(res[2] === 'c')
141 })
142```
143
144#### Promise.any(array)
145
146Returns a single promise that fulfills as soon as any of the promises in the iterable fulfills, with the value of the fulfilled promise. If no promises in the iterable fulfill (if all of the given promises are rejected), then the returned promise is rejected with an `AggregateError`
147
148```js
149var rejected = Promise.reject(0);
150var first = new Promise(function (resolve){ setTimeout(resolve, 100, 'quick') });
151var second = new Promise(function (resolve){ setTimeout(resolve, 500, 'slow') });
152
153var promises = [rejected, first, second];
154
155Promise.any(promises) // => succeeds with `quick`
156```
157
158#### Promise.allSettled(array)
159
160Returns a promise that resolves after all of the given promises have either fulfilled or rejected, with an array of objects that each describes the outcome of each promise.
161
162```js
163Promise.allSettled([Promise.resolve('a'), Promise.reject('error'), Promise.resolve('c')])
164 .then(function (res) {
165 res[0] // { status: "fulfilled", value: 'a' }
166 res[1] // { status: "rejected", reason: 'error' }
167 res[2] // { status: "fulfilled", value: 'c' }
168 })
169```
170
171#### Promise.race(array)
172
173Returns a promise that resolves or rejects with the result of the first promise to resolve/reject, e.g.
174```js
175var rejected = Promise.reject(new Error('Whatever'));
176var fulfilled = new Promise(function (resolve) {
177 setTimeout(() => resolve('success'), 500);
178});
179
180var race = Promise.race([rejected, fulfilled]);
181// => immediately rejected with `new Error('Whatever')`
182
183var success = Promise.resolve('immediate success');
184var first = Promise.race([success, fulfilled]);
185// => immediately succeeds with `immediate success`
186```
187
188#### Promise.denodeify(fn)
189
190_Non Standard_
191
192Takes a function which accepts a node style callback and returns a new function that returns a promise instead.
193
194e.g.
195
196```javascript
197var fs = require('fs')
198
199var read = Promise.denodeify(fs.readFile)
200var write = Promise.denodeify(fs.writeFile)
201
202var p = read('foo.json', 'utf8')
203 .then(function (str) {
204 return write('foo.json', JSON.stringify(JSON.parse(str), null, ' '), 'utf8')
205 })
206```
207
208#### Promise.nodeify(fn)
209
210_Non Standard_
211
212The twin to `denodeify` is useful when you want to export an API that can be used by people who haven't learnt about the brilliance of promises yet.
213
214```javascript
215module.exports = Promise.nodeify(awesomeAPI)
216function awesomeAPI(a, b) {
217 return download(a, b)
218}
219```
220
221If the last argument passed to `module.exports` is a function, then it will be treated like a node.js callback and not parsed on to the child function, otherwise the API will just return a promise.
222
223### Prototype Methods
224
225These methods are invoked on a promise instance by calling `myPromise.methodName`
226
227### Promise#then(onFulfilled, onRejected)
228
229This method follows the [Promises/A+ spec](http://promises-aplus.github.io/promises-spec/). It explains things very clearly so I recommend you read it.
230
231Either `onFulfilled` or `onRejected` will be called and they will not be called more than once. They will be passed a single argument and will always be called asynchronously (in the next turn of the event loop).
232
233If the promise is fulfilled then `onFulfilled` is called. If the promise is rejected then `onRejected` is called.
234
235The call to `.then` also returns a promise. If the handler that is called returns a promise, the promise returned by `.then` takes on the state of that returned promise. If the handler that is called returns a value that is not a promise, the promise returned by `.then` will be fulfilled with that value. If the handler that is called throws an exception then the promise returned by `.then` is rejected with that exception.
236
237#### Promise#catch(onRejected)
238
239Sugar for `Promise#then(null, onRejected)`, to mirror `catch` in synchronous code.
240
241#### Promise#done(onFulfilled, onRejected)
242
243_Non Standard_
244
245The same semantics as `.then` except that it does not return a promise and any exceptions are re-thrown so that they can be logged (crashing the application in non-browser environments)
246
247#### Promise#nodeify(callback)
248
249_Non Standard_
250
251If `callback` is `null` or `undefined` it just returns `this`. If `callback` is a function it is called with rejection reason as the first argument and result as the second argument (as per the node.js convention).
252
253This lets you write API functions that look like:
254
255```javascript
256function awesomeAPI(foo, bar, callback) {
257 return internalAPI(foo, bar)
258 .then(parseResult)
259 .then(null, retryErrors)
260 .nodeify(callback)
261}
262```
263
264People who use typical node.js style callbacks will be able to just pass a callback and get the expected behavior. The enlightened people can not pass a callback and will get awesome promises.
265
266## Enterprise Support
267
268Available as part of the Tidelift Subscription
269
270The maintainers of promise and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-promise?utm_source=npm-promise&utm_medium=referral&utm_campaign=enterprise&utm_term=repo)
271
272## License
273
274 MIT
Note: See TracBrowser for help on using the repository browser.