Table of Contents
Promise in js
Concept
Basic api
1. .then 方式顺序调用2. 设定更高层的作用域3. spread
Copy after login
" >
1. .then 方式顺序调用2. 设定更高层的作用域3. spread
Copy after login
任何情况下都会执行的,一般写在 catch 之后
Copy after login
" >
任何情况下都会执行的,一般写在 catch 之后
Copy after login
用于处理一个数组,或者 promise 数组,
Copy after login
" >
用于处理一个数组,或者 promise 数组,
Copy after login
ASYNC
Home Web Front-end JS Tutorial The artifact in Javascript - Promise

The artifact in Javascript - Promise

Feb 10, 2017 am 09:58 AM
javascript promise

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
});
Copy after login

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]);
    Copy after login

  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
    });
Copy after login

We You can do three things,

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

1. Encapsulate synchronous and asynchronous code

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

"
Promise.resolve(someValue);
"
Copy after login

2. Capture synchronization exceptions

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

If it is synchronous code, it can be written as

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

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
});
Copy after login

4. Get the return value of two Promise

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

5. finally

任何情况下都会执行的,一般写在 catch 之后
Copy after login

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;
});
Copy after login

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;
});
Copy after login

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);
});
"
Copy after login

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);
});
"
Copy after login

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) {
Copy after login

err.forEach(function(e) {

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

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

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

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

Option: concurrency and found

    map(..., {concurrency: 1});
Copy after login

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);
});
Copy after login

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
Copy after login

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
});
Copy after login
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 of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

Keeping your word: The pros and cons of delivering on your promises Keeping your word: The pros and cons of delivering on your promises Feb 18, 2024 pm 08:06 PM

In daily life, we often encounter problems between promises and fulfillment. Whether in a personal relationship or a business transaction, delivering on promises is key to building trust. However, the pros and cons of commitment are often controversial. This article will explore the pros and cons of commitments and give some advice on how to keep your word. The promised benefits are obvious. First, commitment builds trust. When a person keeps his word, he makes others believe that he is a trustworthy person. Trust is the bond established between people, which can make people more

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Learn more about Promise.resolve() Learn more about Promise.resolve() Feb 18, 2024 pm 07:13 PM

Detailed explanation of Promise.resolve() requires specific code examples. Promise is a mechanism in JavaScript for handling asynchronous operations. In actual development, it is often necessary to handle some asynchronous tasks that need to be executed in sequence, and the Promise.resolve() method is used to return a Promise object that has been fulfilled. Promise.resolve() is a static method of the Promise class, which accepts a

See all articles