What does a Promise object do?
Answer: The method of operation asynchronous use.
This chapter blog briefly introduces the use of promise. It is not difficult to read it patiently.
Students who have studied javascript should be aware that js is single-threaded in the process, that is, the code is parsed at the same time. Sometimes, asynchronous operation is necessary. Before there is no promise, we usually use a callback function and add a delay execution to achieve this function, for example:
function foo(){ setTimeout(()=>{ // Asynchronous code },1000) }
The disadvantage of callback function method is that it can produce callback hell when doing multiple asynchronous operations, which has a great impact on performance. Such as:
// Perform asynchronous operations every 2 seconds function foo(i){ setTimeout(()=>{ i(); },2000); } foo(function(){ console.log("Asynchronous operation 1"); foo(function(){ console.log("Asynchronous operation 2"); foo(function(){ console.log("Asynchronous operation 3"); foo(function(){ console.log("Asynchronous operation 4"); foo(function(){ console.log("Asynchronous operation 5"); }); }); }); }); }); // It's a magical callback hell, endless, nested in layers.
After ES6, Promise objects appeared, which would solve the problem of callback hell by implementing asynchronous operations.
Promise specification:
To construct the Promise initials, capitalize:
var pro = new Promise() // title case
promise has three states, and once a request is made, it can not terminate, and the state is irreversible, nor can it change again! The following three states should be noted down and asked during the interview.
pending (waiting) fulfilled rejected (incomplete)
Two threads,
One is from pending to fulfilled. One is from pending to rejected.
There are two ways for these two states, one is
then // Successfully go then
The other is
catch // Failure to go catch
So when we use Promise, we can use these two methods to achieve the operation after success and the operation after failure.
So how do we change the state? In the Promise object, two methods resolve() and reject() are provided.
Resolution (): pending state - > fulfilled state // resolve() changes the "wait" state to the "complete" state reject(): pending state - > rejected state // reject() changes the "wait" state to the "uncompleted" state
Let's not be confused. First, we can understand these conceptual problems. We can give examples.
function foo(){ var pro = new Promise(function(resolve,reject){ resolve(); // Resolution () method, which makes the state complete, so go then instead of catch }); return pro; // Note: You need to throw back the Promise object, otherwise you will report an error. } foo().then(function(){ console.log('Success'); }).catch(function(){ console.log('fail'); }); // When printed, the result is "successful" // Because there is a resolve() method above, so the state is changed to a successful state, so go after the code. // If you change the resolve() method to reject(), the result becomes "failure".
The above case is very basic, so you will understand it.
In addition to this single asynchronous operation, Promise can continue to do several asynchronous, perfect solution to the problem of callback hell. Such as:
function foo(){ var pro = new Promise(function(resolve,reject){ setTimeout(()=>{ resolve(); },2000) }) return pro; } foo() .then(()=>{ console.log('Asynchronous operation 1') return foo(); }) .then(()=>{ console.log('Asynchronous operation 2') return foo(); }) .then(()=>{ console.log('Asynchronous operation 3') return foo(); }) .then(()=>{ console.log('Asynchronous operation 4') return foo(); }) .then(()=>{ console.log('Asynchronous operation 5') return foo(); }) // Output results are printed every 2 seconds. // If you want to write a few asynchronous operations, write a few, which solves the problem of callback hell.
In addition, Promise can also perform asynchronous tasks in parallel, with two methods, all() and race().
all() multiple asynchronous operations are completed before then(); one failed return race() multiple asynchronous operations, who triggered the state first, who returned the results, and then triggered will not return the results.
It's also very simple to use. The method uses arrays:
Promise.all( [ A(), B(), C(), D() ] ).then() Promise.race( [ A(), B(), C(), D() ] ).then()
Let's take an example of all():
Imagine the game of King Glory. The games of many players are loaded to 100% before they start to enter the opening page of the game.
function zhenJi(){ var zj = new Promise(function(resolve,reject){ setTimeout(()=>{ console.log("Yan Ji is loading...") resolve() },2000) }) return zj } function yaSe(){ var ys = new Promise(function(resolve,reject){ setTimeout(()=>{ console.log("Arthur is loading...") resolve() },3000) }) return ys } Promise.all([zhenJi(),yaSe()]).then(()=>{ console.log('The Game Begins') }) // 2s and then output "Zhenji Loading..." "Arthur Loading..." is output at the same time after 3s. "Game Begins"
The race() method is the same, but it returns which one is executed first.
var a1 = new Promise(function (resolve, reject) { setTimeout(resolve, 500, 'Zhen Ji'); }); var a2 = new Promise(function (resolve, reject) { setTimeout(resolve, 600, ',Arthur'); }); Promise.race([p1, p2]).then(function (result) { console.log(result); // 'Zhenji' });
Attention should be paid to some problems:
Don't forget a few ways. Keep a few states in mind.
The successful way is then, the failure way is catch.
promise is executed immediately, but don't forget to execute asynchronously.