search
HomeWeb Front-endJS TutorialThe artifact in Javascript - Promise

The artifact in Javascript - Promise

Feb 10, 2017 am 09:58 AM
javascriptpromise

Promise in js

The real problem with callback functions is that they take away our ability to use the return and throw keywords. And Promise solves all this very well.

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

ECMAScript is the international standard for the JavaScript language, and JavaScript is the implementation of ECMAScript. The goal of ES6 is to enable the JavaScript language to be used to write 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 transmit messages for asynchronous operations. It represents an event (usually an asynchronous operation) whose result is not known until the future, and this event provides a unified API for further processing.

Promise objects have the following two characteristics.

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

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

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

Promise also has some disadvantages. First of all, Promise cannot be canceled. Once it is created, it will be executed immediately and cannot be canceled midway. Secondly, if the callback function is not set, errors thrown internally by Promise will not be reflected externally. Third, when in the Pending state, it is impossible to know which stage the current progress is (just started or about to be completed).

var promise = new Promise(function(resolve, reject) { if (/* 异步操作成功 */){
 resolve(value);
 } else {
 reject(error);
 }
});

promise.then(function(value) { // success
}, function(value) { // failure
});

The Promise constructor accepts a function as a parameter. 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 "uncompleted" to "successful" (that is, from pending to resolved);

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

Basic api

  1. ##Promise.resolve()

  2. Promise.reject()

  3. Promise.prototype.then()

  4. Promise.prototype.catch()

  5. Promise.all() // All completed

     var p = Promise.all([p1,p2,p3]);

  6. Promise.race() // Racing, just complete one

Advanced

The wonder of promises is that given our previous return and throw, each Promise will provide a then() function and a catch(), which is actually a then(null, ...) function.

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

We You can do three things,

1. return 另一个 promise2. return 一个同步的值 (或者 undefined)3. throw 一个同步异常 ` throw new Eror('');`

1. Encapsulate synchronous and asynchronous code

"
new Promise(function (resolve, reject) {
 resolve(someValue);
 });
"
写成

"
Promise.resolve(someValue);
"

2. Capture synchronization exceptions

 new Promise(function (resolve, reject) { throw new Error('悲剧了,又出 bug 了');
 }).catch(function(err){ console.log(err);
 });

If it is synchronous 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 value of two Promise

1. .then 方式顺序调用2. 设定更高层的作用域3. spread

5. finally

任何情况下都会执行的,一般写在 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 this

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,

  1. You must declare it first, there is a waste of resources and memory Risk of leakage

  2. Cannot be used in the context of an expression

  3. Less efficient

7. all. Very useful for processing a dynamically sized Promise list

8. join. Ideal for handling multiple detached 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. Handle a map collection of promises. Only if one fails, all executions end

"
Promise.props({ pictures: getPictures(),
 comments: getComments(),
 tweets: getTweets()
}).then(function(result) {
 console.log(result.tweets, result.pictures, result.comments);
});
"

10. any, some, race

"Promise.some([
 ping("ns1.example.com"),
 ping("ns2.example.com"),
 ping("ns3.example.com"),
 ping("ns4.example.com")
], 2).spread(function(first, second) { console.log(first, second);
}).catch(AggregateError, function(err) {

err.forEach(function(e) {

console.error(e.stack );
});
});;

"
有可能,失败的 promise 比较多,导致,Promsie 永远不会 fulfilled

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

用于处理一个数组,或者 promise 数组,

Option: concurrency and found

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

The following is unlimited number of concurrency, reading file information

var Promise = require("bluebird");
var join = Promise.join;
var fs = Promise.promisifyAll(require("fs"));
var concurrency = parseFloat(process.argv[2] || "Infinity");
var fileNames = ["file1.json", "file2.json"];
Promise.map(fileNames, function(fileName) { 
return fs.readFileAsync(fileName)
 .then(JSON.parse)
 .catch(SyntaxError, function(e) {
 e.fileName = fileName; throw e;
 })
}, {concurrency: concurrency}).then(function(parsedJSONs) { console.log(parsedJSONs);
}).catch(SyntaxError, function(e) { console.log("Invalid JSON in file " + e.fileName + ": " + e.message);
});

Result

$ sync && echo 3 > /proc/sys/vm/drop_caches
$ node test.js 1reading 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.reduce(["file1.txt", "file2.txt", "file3.txt"], 
function(total, fileName) { 
return fs.readFileAsync(fileName, "utf8").then(
function(contents) { 
return total + parseInt(contents, 10);
 });
}, 0).then(function(total) { //Total is 30
});

12. Time

  1. .delay(int ms) -> Promise

  2. ##.timeout(int ms [, String message] ) -> Promise
  3. Promise implementation

    q
  1. ##bluebird
  2. co
  3. when

ASYNC

The async function, like the Promise and Generator functions, is a method used to replace callback functions and solve asynchronous operations. It is essentially syntactic sugar for the Generator function. async functions are not part of ES6, but are included in ES7.

The above is the content of Promise, the artifact in Javascript. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)