search
HomeWeb Front-endJS TutorialWhat is Promise in ECMAScript6? What is the use? (with examples)

The content of this article is about what is Promise in ECMAScript6? What is the use? (With examples), it has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

I just finished studying and have a rough impression. Organize and record it for subsequent study and supplement to deepen your understanding.

What is Promise

Promise is a constructor that can generate Promise objects through new.

What is the use of Promise

My current feeling is: it is more convenient to operate asynchronous processes, the process of controlling events is clearer and more intuitive, and chain calls can be made

Promise Characteristics

Excerpted from ES6 Getting Started

The Promise object has 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), fulfilled (successful) 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. Its English meaning is "commitment", which 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 fulfilled and from pending to rejected. As long as these two situations occur, the state will solidify, will not change again, and will maintain this result. This is called resolved. 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.

Understand it through a few simple examples

Construct a simple Promise object through new

let p = new Promise((resolve, reject) => {});

The two parameters passed in are used to control the state of the Promise object. We Print p to see its status:
Promise {__proto__: Promise[[PromiseStatus]]: "pending"[[PromiseValue]]: undefinedThis is the initial state pending
And resolve, Reject can control the state of Promise

//resolve()
let p = new Promise((resolve, reject) => resolve("123")); //Promise {<resolved>: "123"}</resolved>
//reject()
let p = new Promise((resolve, reject) => reject("123")); //reject()后是返回一个失败状态的Promise,不需要用catch来捕获不写catch会报错
p.catch(data => console.log(data));    
console.log(p);    //Promise {<rejected>: "123"}   123</rejected>

Mentioned catch, there is also then
Let’s keep it simple: then(f1, f2) can fill in two function parameters, one parameter is resolve Substitute the middle parameter into f1 to execute, and the second parameter substitute the parameter in reject into f2 to execute; the second parameter can be replaced by catch, and it is more powerful. Catch can capture the error in then()

let p = new Promise((resolve, reject) => {
    
    let n = Math.ceil(Math.random() * 10);
    n > 5 ? resolve(n) : reject(n);
});
p.then(
    data => console.log(data),
    data => console.log(data),
)

Use catch instead, and capture the error of then

let p = new Promise((resolve, reject) => {
    
    resolve("yes")
});
p.then(
    data => {console.log(data),console.log(a)}

).catch(data => console.log(data));
//yes
//ReferenceError: a is not defined

Because the Promise object is returned after then processing, which facilitates chain calls. There is no return in then, so how can there be a Promise object?

then or catch even if the return value is not explicitly specified, they always automatically wrap a new fulfilled state promise object.

When we print it, we will find: Promise {<resolved>: undefined}</resolved>
Then we can display a return Promise object and see,

let p = new Promise((resolve, reject) => resolve("yes"));
p.then(data => Promise.resolve("第二个Promise")).then(data => console.log(data));   //第二个Promise

can seep.then(data => Promise.resolve("Second Promise"))The returned Promise object is Promise {<resolved>: "Second Promise"}</resolved>and Pass the value as a parameter into the second then to execute

Promise.resolve(value | promise | thenable) to create a Promise object
The first parameter is empty or original value, and the Promise object is created The state is directly resolved state

Promise.resolve('f')
// 等价于
new Promise(resolve => resolve('f'))

The secondIt is worth noting that the object with the then method

let thenable = {
    then :(resolve, reject) => resolve("thenable")
}

let p = Promise.resolve(thenable);
console.log(p);

The Promise object state is determined by-> The third parameter is the instantiated Promise object,

let p1 = new Promise((resolve, reject) => false);
let p = Promise.resolve(p1);
console.log(p);

p state is consistent with p1 state

Promise.reject(value) creates a Promise object
Different from resolve Yes: directly pass the value as a parameter into the

const thenable = {
  then(resolve, reject) {
    reject('出错了');
  }
};

Promise.reject(thenable)
.catch(e => {
  console.log(e === thenable)
})

catch method. The parameter of the catch method is not the "error" string thrown by reject, but the thenable object.

Promise.all

Wrap multiple Promise instances into a new Promise instance; const p = Promise.all([p1, p2, p3]);

(1) Only when the status of p1, p2, and p3 all become fulfilled, will the status of p become fulfilled. At this time, the return values ​​of p1, p2, and p3 form an array and are passed to the callback function of p.

(2) As long as one of p1, p2, and p3 is rejected, the status of p will become rejected. At this time, the return value of the first rejected instance will be passed to the callback function of p. .

Will wait for all objects in all to be executed and then pass the array into the callback function then

let p = new Promise((resolve, reject) => setTimeout(() => resolve('p'),1000));
let p1 = new Promise((resolve, reject) => setTimeout(() => resolve('p2'),2000));
let p2 = new Promise((resolve, reject) => setTimeout(() => resolve('p3'),3000));
Promise.all([p, p1, p2]).then(data => console.log(data)).catch(data => console.log(data));    // ["p", "p2", "p2"]
let p = new Promise((resolve, reject) => resolve('p'));
let p1 = new Promise((resolve, reject) => reject('p2'));
let p2 = new Promise((resolve, reject) => resolve('p2'));
Promise.all([p, p1, p2]).then(data => console.log(data)).catch(data => console.log(data));   //p2

Promise.race
The difference from all is: as long as p1, p2, p3 One of the instances changes state first, and the state of p changes accordingly. The return value of the Promise instance that changed first is passed to p's callback function.

let p = new Promise((resolve, reject) => setTimeout(() => resolve('p'),1000));
let p1 = new Promise((resolve, reject) => setTimeout(() => resolve('p2'),2000));
let p2 = new Promise((resolve, reject) => setTimeout(() => resolve('p3'),3000));
Promise.race([p, p1, p2]).then(data => console.log(data)).catch(data => console.log(data));   //p

The order of the callback function and setTimeout of the Promise object

An event loop has one or more task queues. A task queue is an ordered list of tasks, which are algorithms that are responsible for such work as: events, parsing, callbacks, using a resource, reacting to DOM manipulation…Each event loop has a microtask queue. A microtask is a task that is originally to be queued on the microtask queue rather than a task queue.
  浏览器(或宿主环境) 遵循队列先进先出原则, 依次遍历macrotask queue中的每一个task, 不过每执行一个macrotask, 并不是立即就执行下一个, 而是执行一遍microtask queue中的任务, 然后切换GUI线程重新渲染或垃圾回收等.
  Event Loop (事件循环)拥有如下两种队列
  macrotask queue, 指的是宏任务队列, 包括rendering, script(页面脚本), 鼠标, 键盘, 网络请求等事件触发, setTimeout, setInterval, setImmediate(node)等等.
  microtask queue, 指的是微任务队列, 用于在浏览器重新渲染前执行, 包含Promise, process.nextTick(node), Object.observe, MutationObserver回调等.
  process.nextTick > promise.then > setTimeout ? setImmediate

setTimeout(function () {
  console.log('three');
}, 0);

Promise.resolve().then(function () {
  console.log('two');
});

console.log('one');

// one
// two
// three

上面代码中,setTimeout(fn, 0)在下一轮“事件循环”开始时执行,Promise.resolve()在本轮“事件循环”结束时执行,console.log('one')则是立即执行,因此最先输出。

setTimeout(function() {
  console.log(4)
}, 0);
new Promise(function(resolve) {
  console.log(1);
  for (var i = 0; i <p class="comments-box-content"></p>

The above is the detailed content of What is Promise in ECMAScript6? What is the use? (with examples). For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:segmentfault思否. If there is any infringement, please contact admin@php.cn delete
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.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function