Promise is a function in ES6 that specifies how to handle callback functions for asynchronous tasks. Its function is similar to jQuery's defferred. Simply put, different callback functions are called through different states of the promise object. Currently IE8 and below are not supported, but other browsers are.
The state of the promise object will not change after it is converted from Pending to Resolved or Rejected.
Usage steps:
var promise = new Promise(function(resolve, reject) { // 异步任务,通过调用resolve(value) 或 reject(error),以改变promise对象的状态;改变状态的方法只能在此调用。 //promise状态改变后,会调用对应的回调方法 }); promise.then(function(value){//resolve时的回调函数,参数由异步的函数传进来}) .catch(function(error){//发生异常时或明确reject()时的回调函数})
Specific usage:
function getURL(URL) { //因为promise创建时即执行,所以用工厂函数封装promise对象 return new Promise(function (resolve, reject) { var req = new XMLHttpRequest(); req.open('GET', URL, true); req.onload = function () { if (req.status === 200) { resolve(req.responseText); } else { reject(new Error(req.statusText)); } }; req.onerror = function () { reject(new Error(req.statusText)); }; req.send(); }); } // 运行示例 var URL = "http://httpbin.org/get"; getURL(URL).then(function onFulfilled(value){ console.log(value); }).catch(function onRejected(error){ console.error(error); })
The callback of Promise is only asynchronous, even the callback of a synchronous task is executed asynchronously.
var promise = new Promise(function (resolve){ console.log("inner promise"); // 执行1:同步任务先执行 resolve(‘callBack'); }); promise.then(function(value){ console.log(value); // 执行3:虽然注册时状态为resolved,但回调仍是异步的; }); console.log("outer promise"); // 执行2:同步代码先执行
Promise method chain
The callbacks registered by the then method will be called in sequence, and parameters are passed through the return value between each then method. However, exceptions in the callback will cause the then callback to be skipped, the catch callback to be called directly, and then the remaining then callbacks to be called. In then(onFulfilled, onRejected), the onFulfilled exception will not be caught by its own onRejected, so catch is used first.
promise .then(taskA) .then(taskB) .catch(onRejected) .then(finalTask);
taskA throws an exception, taskB is skipped, and finalTask will still be called, because The status of the promise object returned by catch is resolved.
The then method can return 3 kinds of values
1. Return another promise object. The next then method selects the onFullfilled/onRejected callback function to execute according to its status. The parameters are still determined by the resolv of the new promise. /reject method delivery;
2. Returns a synchronous value. The next then method uses the state of the current promise object and will be executed immediately without waiting for the asynchronous task to end; the actual parameter is the return value of the previous then; if not return, the default return is undefined;
3. Throw an exception (synchronous/asynchronous): throw new Error('xxx');
then not only registers a callback function, but also The return value of the callback function is transformed, creating and returning a new promise object. In fact, Promise does not operate on the same promise object in the method chain.
var aPromise = new Promise(function (resolve) { resolve(100); }); var thenPromise = aPromise.then(function (value) { console.log(value); }); var catchPromise = thenPromise.catch(function (error) { console.error(error); }); console.log(aPromise !== thenPromise); // => true console.log(thenPromise !== catchPromise);// => true
Promise.all() static method, perform multiple asynchronous tasks at the same time. Subsequent processing will not continue until all received promise objects become FulFilled or Rejected.
Promise.all([promiseA, promiseB]).then(function(results){//results是个数组,元素值和前面promises对象对应}); // 由promise对象组成的数组会同时执行,而不是一个一个顺序执行,开始时间基本相同。 function timerPromisefy(delay) { console.log('开始时间:”'+Date.now()) return new Promise(function (resolve) { setTimeout(function () { resolve(delay); }, delay); }); } var startDate = Date.now(); Promise.all([ timerPromisefy(100), //promise用工厂形式包装一下 timerPromisefy(200), timerPromisefy(300), timerPromisefy(400) ]).then(function (values) { console.log(values); // [100,200,300,400] });
Does not execute simultaneously, but executes promises one after another
//promise factories返回promise对象,只有当前异步任务结束时才执行下一个then function sequentialize(promiseFactories) { var chain = Promise.resolve(); promiseFactories.forEach(function (promiseFactory) { chain = chain.then(promiseFactory); }); return chain; }
Promise.race() is similar to all(), but race() only needs one promise object to enter the FulFilled or Rejected state If so, the corresponding callback function will be executed. However, after the first promise object becomes Fulfilled, it does not affect the continued execution of other promise objects.
//沿用Promise.all()的例子 Promise.race([ timerPromisefy(1), timerPromisefy(32), timerPromisefy(64), timerPromisefy(128) ]).then(function (value) { console.log(values); // [1] });
The wonderful use of Promise.race() as a timer
Promise.race([ new Promise(function (resolve, reject) { setTimeout(reject, 5000); // timeout after 5 secs }), doSomethingThatMayTakeAwhile() ]);
Changing the promise state in then
Because there are only value parameters in the callback of then, there is no way to change the state (Can only be used in the asynchronous task of the constructor). If you want to change the state of the promise object passed to the next then, you can only create a new Promise object, determine whether to change the state in the asynchronous task, and finally return it to pass. Give the next then/catch.
var promise = Promise.resolve(‘xxx');//创建promise对象的简介方法 promise.then(function (value) { var pms=new Promise(function(resolve,reject){ setTimeout(function () { // 在此可以判断是否改变状态reject/resolve Reject(‘args'); }, 1000); }) return pms; //该promise对象可以具有新状态,下一个then/catch需要等异步结束才会执行回调;如果返回普通值/undefined,之后的then/catch会立即执行 }).catch(function (error) { // 被reject时调用 console.log(error) });
Get the results of two promises
//方法1:通过在外层的变量传递 var user; getUserByName('nolan').then(function (result) { user = result; return getUserAccountById(user.id); }).then(function (userAccount) { //可以访问user和userAccount }); //方法2:后一个then方法提到前一个回调中 getUserByName('nolan').then(function (user) { return getUserAccountById(user.id).then(function (userAccount) { //可以访问user和userAccount }); });
Pay attention to the overall structure when using promise
Assume that both doSomething() and doSomethingElse() return promise objects
Commonly used methods:
doSomething().then(doSomethingElse).then(finalHandler); doSomething |-----------------| doSomethingElse(resultOfDoSomething) //返回新promise,下一个then要收到新状态才执行 |------------------| finalHandler(resultOfDoSomethingElse) |---------------------|
Commonly used workarounds:
doSomething().then(function () { return doSomethingElse();}).then(finalHandler); doSomething |-----------------| doSomethingElse(undefined) //then外层函数的arguments[0]== resultOfDoSomething |------------------| finalHandler(resultOfDoSomethingElse) |------------------|
Error method 1:
doSomething().then(function () { doSomethingElse();}).then(finalHandler); doSomething |-----------------| doSomethingElse(undefined) //虽然doSomethingElse会返回promise对象,但最外层的回调函数是return undefined,所以下一个then方法无需等待新promise的状态,会马上执行回调。 |------------------| finalHandler(undefined) |------------------|
Error method 2:
doSomething().then(doSomethingElse()).then(finalHandler); doSomething |-----------------| doSomethingElse(undefined) //回调函数在注册时就直接被调用 |----------| finalHandler(resultOfDoSomething) |------------------|
More Promises in JavaScript For articles related to the use of PHP, please pay attention to the PHP Chinese website!

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

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.

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 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 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.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Chinese version
Chinese version, very easy to use

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),