Home >Web Front-end >JS Tutorial >What is Promise in ECMAScript6? What is the use? (with examples)

What is Promise in ECMAScript6? What is the use? (with examples)

不言
不言forward
2018-10-24 11:44:472082browse

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"}
//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

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}
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"}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>
<p>p state is consistent with p1 state </p>
<p>Promise.reject(value) creates a Promise object<br> Different from resolve Yes: directly pass the value as a parameter into the </p>
<pre class="brush:php;toolbar:false">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 < 10000; i++) {
    i == 9999 && resolve()
  }
  console.log(2);
}).then(function() {
  console.log(5)
});
console.log(3);  //1 2 3 5 4

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.com. If there is any infringement, please contact admin@php.cn delete