Artifact in Javascript Promise

  • 2021-07-18 06:42:30
  • OfStack

Promise in js

The real problem with the callback function is that it deprives us of the ability to use the keywords return and throw. And Promise solves this 1 cut well.

In June 2015, the official version of ECMAScript 6 was finally released.

ECMAScript is the international standard of JavaScript and JavaScript is the implementation of ECMAScript. The goal of ES 6 is to make JavaScript language can be used to write large and complex applications and become an enterprise development language.

Concept

Promise objects are provided native to ES6.

The so-called Promise is an object used to pass the message of asynchronous operation. It represents an event (usually an asynchronous operation) whose result will not be known in the future, and this event provides API of the whole system, which can be processed in the next step.

The Promise object has two characteristics.

(1) The state of the object is not affected by the outside world. The Promise object represents an asynchronous operation with three states: Pending (in progress), Resolved (completed, also known as Fulfilled), and Rejected (failed). Only the result of an asynchronous operation can determine which state is currently in, and no other operation can change this state. This is the origin of the name Promise, which means "promise" in English, meaning that other means cannot be changed.

(2) Once the state changes, it will not change again, and this result can be obtained at any time. There are only two possibilities for the state change of an Promise object: from Pending to Resolved and from Pending to Rejected. As long as these two conditions occur, the state will solidify, will not change again, and will keep this result. If you add a callback function to the Promise object, even if the change has already occurred, you will get this result immediately. This is completely different from the event (Event). The characteristic of the event is that if you miss it and listen, you will not get the result.

With the Promise object, asynchronous operations can be expressed as the flow of synchronous operations, avoiding layers of nested callback functions. In addition, the Promise object provides a unified interface, making it easier to control asynchronous operations.

Promise also has one drawback. First of all, Promise cannot be cancelled, and it will be executed immediately as soon as it is newly created, so it cannot be cancelled halfway. Secondly, if the callback function is not set, the errors thrown inside Promise will not be reflected to the outside. Third, when in Pending state, it is impossible to know which stage (just started or about to be completed) is currently progressing.


var promise = new Promise(function(resolve, reject) {
 if (/*  Asynchronous operation succeeded  */){
 resolve(value);
 } else {
 reject(error);
 }
});
promise.then(function(value) {
 // success
}, function(value) {
 // failure
});

The Promise constructor takes one function as an argument, and the two arguments to the function are the resolve method and the reject method.

If the asynchronous operation is successful, the state of Promise object is changed from "incomplete" to "successful" (i.e. from pending to resolved) by resolve method;

If the asynchronous operation fails, the reject method is used to change the state of the Promise object from "incomplete" to "failed" (that is, from pending to rejected).

Basic api


Promise.resolve()
Promise.reject()
Promise.prototype.then()
Promise.prototype.catch()
Promise.all() //  Completion of all 
 var p = Promise.all([p1,p2,p3]);
Promise.race() //  Race, finish 1 One is enough 

Advanced

The wonder of promises is that it gives us the previous return and throw. Each Promise will provide an then () function and an catch (), which is actually an then (null,...) function.


 somePromise().then(functoin(){
  // do something
 });

There are three things we can do,

1. return Another promise

2. return 1 synchronized value (or undefined)

3. throw 1 synchronization exception ` throw new Eror (''); `

1. Encapsulate synchronous and asynchronous code


```
new Promise(function (resolve, reject) {
 resolve(someValue);
 });
```

Write as


```
Promise.resolve(someValue);
```

2. Capture synchronization exceptions


 new Promise(function (resolve, reject) {
 throw new Error(' Tragedy, it's out again  bug  It's over ');
 }).catch(function(err){
 console.log(err);
 });

If it is synchronization code, it can be written as

Promise.reject(new Error("什么鬼"));

3. Multiple exception capture, more accurate capture


somePromise.then(function() {
 return a.b.c.d();
}).catch(TypeError, function(e) {
 //If a is defined, will end up here because
 //it is a type error to reference property of undefined
}).catch(ReferenceError, function(e) {
 //Will end up here if a wasn't defined at all
}).catch(function(e) {
 //Generic catch-the rest, error wasn't TypeError nor
 //ReferenceError
});

4. Get the return values of the two Promise

1.. Sequential call in then mode
2. Set a higher level of scope
3. spread

5. finally

It will be executed in any case, and 1 is generally written after catch

6. bind


somethingAsync().bind({})
.spread(function (aValue, bValue) {
 this.aValue = aValue;
 this.bValue = bValue;
 return somethingElseAsync(aValue, bValue);
})
.then(function (cValue) {
  return this.aValue + this.bValue + cValue;
});

Or you can do the same


var scope = {};
somethingAsync()
.spread(function (aValue, bValue) {
 scope.aValue = aValue;
 scope.bValue = bValue;
 return somethingElseAsync(aValue, bValue);
})
.then(function (cValue) {
 return scope.aValue + scope.bValue + cValue;
});

However, there are many differences.

You must first declare that there is a risk of wasting resources and leaking memory Cannot be used in the context of 1 expression Lower efficiency

7. all. Very useful for handling a dynamically uniform Promise list

8. join. Ideal for handling multiple separate Promise


```
var join = Promise.join;
join(getPictures(), getComments(), getTweets(),
 function(pictures, comments, tweets) {
 console.log("in total: " + pictures.length + comments.length + tweets.length);
});
```

9. props. Handles an map collection of 1 promise. Only 1 failed, and all executions ended


Promise.resolve()
Promise.reject()
Promise.prototype.then()
Promise.prototype.catch()
Promise.all() //  Completion of all 
 var p = Promise.all([p1,p2,p3]);
Promise.race() //  Race, finish 1 One is enough 
0

10. any, some, race


Promise.resolve()
Promise.reject()
Promise.prototype.then()
Promise.prototype.catch()
Promise.all() //  Completion of all 
 var p = Promise.all([p1,p2,p3]);
Promise.race() //  Race, finish 1 One is enough 
1

It is possible that promise will fail so much that Promsie will never fail fulfilled

11. .map(Function mapper [, Object options])

Used to process 1 array, or promise array,

Option: concurrency and found

map(..., {concurrency: 1});

The following is the information of unlimited concurrent number and reading documents


Promise.resolve()
Promise.reject()
Promise.prototype.then()
Promise.prototype.catch()
Promise.all() //  Completion of all 
 var p = Promise.all([p1,p2,p3]);
Promise.race() //  Race, finish 1 One is enough 
2

Results


$ sync && echo 3 > /proc/sys/vm/drop_caches
$ node test.js 1
reading files 35ms
$ sync && echo 3 > /proc/sys/vm/drop_caches
$ node test.js Infinity
reading files: 9ms

11. .reduce(Function reducer [, dynamic initialValue]) - > Promise


Promise.resolve()
Promise.reject()
Promise.prototype.then()
Promise.prototype.catch()
Promise.all() //  Completion of all 
 var p = Promise.all([p1,p2,p3]);
Promise.race() //  Race, finish 1 One is enough 
4

12. Time


Promise.resolve()
Promise.reject()
Promise.prototype.then()
Promise.prototype.catch()
Promise.all() //  Completion of all 
 var p = Promise.all([p1,p2,p3]);
Promise.race() //  Race, finish 1 One is enough 
5

Implementation of Promise

q

bluebird

co

when

ASYNC

async function, like Promise and Generator function, is a method to replace callback function and solve asynchronous operation. It is essentially the syntactic sugar of Generator function. The async function does not belong to ES6, but is listed in ES7.


Related articles: