SoFunction
Updated on 2025-03-01

The artifact in Javascript - Promise

Promise in js

The real problem with the callback function is that it deprives us of using keywords such as return and throw. And Promise solves it all very well.

June 2015,ECMAScript 6 official versionFinally released.

ECMAScript is an international standard for the JavaScript language, and JavaScript is an implementation of ECMAScript. The goal of ES6 is to make the JavaScript language useful for writing large and complex applications and become an enterprise-level development language.

concept

ES6 natively provides Promise objects.

The so-called Promise is an object used to pass messages of asynchronous operations. It represents an event that will only know the result in the future (usually an asynchronous operation), and this event provides a unified API for further processing.

Promise objects have the following 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 asynchronous operation can determine which state it is currently in, and no other operation can change this state. This is also the origin of the name Promise. Its English means "promise", which means that other means cannot be changed.

(2) Once the state changes, it will not change again, and you can get this result at any time. There are only two possible ways to change the state of a Promise object: from Pending to Resolved and from Pending to Rejected. As long as these two situations occur, the state will solidify and will not change again. This result will be maintained. Even if the change has already happened, you will get this result immediately by adding a callback function to the Promise object. This is completely different from an event. The characteristic of an event is that if you miss it and listen to it, you will not get any results.

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

Promise also has some disadvantages. First, the Promise cannot be canceled. Once it is created, it will be executed immediately and cannot be cancelled halfway. Secondly, if the callback function is not set, the error thrown by Promise will not be reflected externally. Third, when in Pending state, it is impossible to know which stage it is currently progressing (it is just beginning or about to be completed).

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

The Promise constructor accepts a function as an argument, and the two parameters of the function are the resolve method and the reject method.

If the asynchronous operation is successful, use the resolve method to change the state of the Promise object from "unfinished" to "success" (that is, from pending to resolved);

If the asynchronous operation fails, the state of the Promise object will be changed from "unfinished" to "failed" (that is, from pending to rejected).

Basic API

()
()
()
()
() // All finished var p = ([p1,p2,p3]);
() // Race, just complete one

Advanced

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

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

We can do three things,

1. return another promise

2. return a synchronized value (or undefined)

3. throw a synchronous exception ` throw new Error('');`

1. Encapsulate synchronous and asynchronous code

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

Written

```
(someValue);
```

2. Capture synchronous exceptions

 new Promise(function (resolve, reject) {
 throw new Error('There is a tragedy, another bug');
 }).catch(function(err){
 (err);
 });

If it is synchronous code, it can be written as

(new Error("What the hell"));

3. Multiple exception capture, more accurate capture

(function() {
 return ();
}).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 value of two promises

1. .then method order call
2. Set higher-level scope
3. spread

5. finally

It will be executed under any circumstances, usually written after catch

6. bind

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

Or you can do this

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

However, there are a lot of differences,

  • You must first declare that there is a risk of wasting resources and memory leaks
  • Cannot be used in the context of an expression
  • Less efficiency

7. all. Very useful for handling a dynamically uniformly sized Promise list

8. Join. Ideal for handling multiple separate promises

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

9. props. Process a map collection of promises. Only one failure, all executions end

```
({
 pictures: getPictures(),
 comments: getComments(),
 tweets: getTweets()
}).then(function(result) {
 (, , );
});
```

10. any 、some、race

```
([
 ping(""),
 ping(""),
 ping(""),
 ping("")
], 2).spread(function(first, second) {
 (first, second);
}).catch(AggregateError, function(err) {
(function(e) {
();
});
});;

```

It is possible that there are many promises that fail, which leads to Promsie never fulfilled

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

Used to process an array, or promise array,

Option: concurrency and discover

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

The following is the information about reading files without limiting the number of concurrency

var Promise = require("bluebird");
var join = ;
var fs = (require("fs"));
var concurrency = parseFloat([2] || "Infinity");
var fileNames = ["", ""];
(fileNames, function(fileName) {
 return (fileName)
 .then()
 .catch(SyntaxError, function(e) {
  = fileName;
 throw e;
 })
}, {concurrency: concurrency}).then(function(parsedJSONs) {
 (parsedJSONs);
}).catch(SyntaxError, function(e) {
 ("Invalid JSON in file " +  + ": " + );
});

result

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

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

(["", "", ""], function(total, fileName) {
 return (fileName, "utf8").then(function(contents) {
 return total + parseInt(contents, 10);
 });
}, 0).then(function(total) {
 //Total is 30
});

12. Time

.delay(int ms) -> Promise
.timeout(int ms [, String message]) -> Promise

The implementation of Promise

q

bluebird

co

when

ASYNC

Like Promise and Generator functions, the async function is a method to replace callback functions and solve asynchronous operations. It is essentially syntactic sugar for the Generator function. The async function does not belong to ES6, but is included in ES7.

The above is all the content of this article. I hope that the content of this article will help you study or work. I also hope to support me more!