1. What is Promise
2. Basic usage The
const promise = new Promise(function(resolve, reject) { // ... if (/* asynchronous operation successful*/){ resolve(value); } else { reject(error); } }); After
promise.then(function (value){ // .... },function (err){ // .... err }) promise.then(function (value){ // .... }).catch(function (err){ // .... }) 3. Promise Methods 3.1 Promise.prototype.then() The The loadData().then(function (value){ return 3 }).then(function (num){ console.log("ok", num) // 3 }) 3.2 Promise.prototype.catch() The const promise = new Promise(function(resolve, reject) { throw new Error('unkonw error'); // throw error state changes to -> reject }); const promise = new Promise(function(resolve, reject) { reject('unkonw error') // Use the reject() method to change the state to -> reject }); promise.catch(function(error) { console.log(error); }); The error of loadData().then(function(value) { return loadData(value); }).then(function(users) { }).catch(function(err) { // Handle errors from the first three Promises }); If we don't set const promise = new Promise(function(resolve, reject) { resolve(a) // ReferenceError: a is not defined }); promise.then(function(value) { console.log('value is ', value) }); setTimeout(() => { console.log('code is run') }, 1000); // code is run 3.3 Promise.prototype.finally() promise .then(result => {···}) .catch(error => {···}) .finally(() => {···}); 3.4 Promise.all() const promise = Promise.all([p1, p2, p3]); The new
const promises = [1,2,3,4].map(function (id) { return loadData(id); }); Promise.all(promises).then(function (users) { // ... }).catch(function(err){ // ... }); 3.5 Promise.race() The parameters of const promise = Promise.race([p1, p2, p3]);
Scenario 1: After a user logs in to the homepage of a social networking site, they will asynchronously request to pull user information, follow list, and fan list. We need to ensure that all data requests are successful before rendering the page. If any data fails, the page will be redirected. Here we can use function initUserHome() { Promise.all([ new Promise(getMe), new Promise(getFollows), new Promise(getFans) ]) .then(function(data){ // Display the page }) .catch(function(err){ // .... redirect page }); }; initUserHome(); Scenario 2: If we are making a ticket grabbing software, although we request many ticket selling channels, we only need to return the first completed Promise each time. Here we can use function getTicket() { Promise.race([ new Promise(postASell), new Promise(postBSell), new Promise(postCSell) ]) .then(function(data){ // Ticket grab success}) .catch(function(err){ // .... failed to grab the ticket, try again}); }; getTicket(); 3.6 Promise.allSettled() When using const requests = [ fetch('/url1'), fetch('/url2'), fetch('/url3'), ]; try { await Promise.all(requests); console.log('All requests were successful.'); } catch { console.log('One request failed, other requests may not have finished yet.'); } Sometimes, we want to wait until a group of asynchronous operations are completed before proceeding to the next step. At this time, you need to use const requests = [ fetch('/url1'), fetch('/url2'), fetch('/url3'), ]; await Promise.allSettled(requests); console.log('Execute after all requests are completed (including success and failure)'); 3.7 Promise.any() As long as one of the incoming Back to the scenario of multi-channel ticket grabbing using function getTicket() { Promise.any([ new Promise(postASell), new Promise(postBSell), new Promise(postCSell) ]) .then(function(data){ // One ticket was successfully grabbed}) .catch(function(err){ // .... all channels failed }); }; getTicket(); 3.8 Promise.resolve() new Promise(resolve => resolve(1)) The parameters passed in are different.
let thenable = { then: function(resolve, reject) { resolve(1); } };
const promise = Promise.resolve(1); promise.then(function (value) { console.log(value) // 1 });
3.9 Promise.reject() The const promise = Promise.reject('unkonw error'); // equivalent to const promise = new Promise((resolve, reject) => reject('unkonw error')) promise.then(null, function (s) { console.log(s) }); //unknown error 4. Simple sceneLoad images asynchronously: function loadImageAsync(url) { return new Promise(function(resolve, reject) { const image = new Image(); image.onload = resolve; image.onerror = reject; image.src = url; }); } Request timeout processing: //Request function request(){ return new Promise(function(resolve, reject){ // code .... resolve('request ok') }) } function timeoutHandle(time){ return new Promise(function(resolve, reject){ setTimeout(function(){ reject('timeout'); }, time); }); } Promise.race([ request(), timeoutHandle(5000) ]) .then(res=>{ console.log(res) }).catch(err=>{ console.log(err) // timeout }) This is the end of this article about front-end You may also be interested in:
|
<<: A brief discussion on the characteristics of CSS float
>>: HTML form tag tutorial (5): text field tag
This article example shares the specific code of ...
The installation of compressed packages has chang...
1. Javascript returns to the previous page history...
I'm looking for a job!!! Advance preparation:...
MySQL replace and replace into are both frequentl...
This article uses the crontab command in the Linu...
MySQL full text search Chinese solution Recently,...
Prepare Environmental information for this articl...
Table of contents 1. Timestamp to date 2. Convert...
Error message: user: 'root' host: `localh...
There are 4 commonly used methods, as follows: 1....
This article introduces Online preview and downlo...
Introduction to border properties border property...
MySQL and connection related timeouts Preface: To...
The previous article on Docker mentioned the cons...