Deep understanding of promise in ES6

Author| Jeskson Source|Dada Front End Bistro

What is Promise

The Promise object is used to represent the final state (completion or failure) of an asynchronous operation and the value it returns.

What is synchronous, asynchronous

Synchronizing tasks can block program execution, such as alert, for

Asynchronous tasks do not block program execution, such as setTimeou

Use Promise, then, catch, finally

Promise.all and Promise.race

Promise.resolve and Promise.reject

Callbacks and Promise

Callback function to request data

function backFunction(fn) {
 setTimeout(function() {
  fn && fn();
 }, 1000);
}

// call
backFunction(function() {
 console.log(1); // 1
 backFunction(function() {
  console.log(2); // 2
   backFunction(function() {
    console.log(3); // 3
   });
 });
});

Promise

function d() {
 return new Promise(resolve = {
  setTimeout(function() {
   resolve(); // What to do when resolve succeeds
  },1000);
  // resolve() is called a second later and is a function
 })
}

d()
 .then(function() {
  console.log(1);
  return d(); // Promise instance
 })
 .then(function() {
  console.log(2);
  return d(); // Promise instance
 }).then(function() {
  console.log(3);
 });

Contrast Callback

// animation
function moveTo(el, x, y, fn) {
 el.style.transform = `translate(${x}px, ${y}px)`;
 setTimeout(function() {
  fn && fn();
 },1000);
}

let el = document.querySelector('div');

document.querySelector('button').addeventListener('click', e
 moveTo(el, 100, 100, function() {
  console.log(1);
  moveTo(el, 200, 200, function() {
   console.log(2);
  });
 })
});
// promise
function moveTo(el,x,y) {
 return new Promise(resolve => {
  el.style.transform = `translate(${x}px, ${y}px)`;
  setTimeout(function() {
   resolve();
  },1000);
 });
}

document.querySelector('button').addEventListener('click', e=>{
 moveTo(el,100,100)
  .then(function() {
   console.log('da');
   return moveTo(el, 200, 200);
  })
  .then(function() {
    console.log('da2');
  }).then(function() {
    console.log('da2');
  });
});

Trust issues

// Use third-party library callbacks
function method(fn) {
 // Callback
 setTimeout(function() {
  // Callback
  fn && fn();
  // Has bug s, can be called more than once
  fn && fn();
 },1000);
}

// Once promise is invoked, succeeds or fails, it cannot be modified

function method() {
 return new Promise(resolve => {
  setTimeout(function() {
   //Success
   resolve();
   // Re-call will not execute
   resolve();
  },1000);
 });
}
// IoC

function method(fn) {
 setTimeout(function() {
  // CCCallFuncN
  fn && fn.call({a:1, b:2)};
  // Change Point
 },1000);
}

function method(fn) {
 return new Promise(resolve => {
  setTimeout(() => {
   resolve();
  },1000);
 });
}

error handling

then(resolve, reject) The second callback in the then method is what you do when you fail

catch Using the then method of the instance, errors can be caught

finally Successfully or not, finally content is bound to execute

function fn(val) {
 return new Promise((resolve, reject) => {
  if(val) {
   resolve(); // When you succeed
  } else {
   reject(); // When Failed
  }
 });
}
fn(false)
 .then( () => {
  console.log("Success");
 }, () => {
  console.log("fail");
 })

function fn(val) {
 return new Promise((resolve, reject) => {
  if(val) {
   resolve(); // When you succeed
  } else {
   reject('404'); // When Failed
  }
 });
}

fn(false)
 .then( () => {
  console.log("Success");
 }, e => {
  console.log(e);
 })

 promise in resolve Only one parameter can be passed, as follows:
 
 function fn(val) {
 return new Promise((resolve, reject) => {
  if(val) {
   resolve({name: 'da'}); // When you succeed
  } else {
   reject('404'); // When Failed
  }
 });
}

fn(true)
 .then( dada => {
  console.log(data);
 }, e => {
  console.log(e);
 })

catch catches errors if they are not handled in the callback

fn(true)
 .then(data => {
  console.log(data);
  return fn(false);
 })
 .then( () => {
  console.log('da'); // No execution, no error handling
 })
 .then( () => {
  
 })
 .catch(e => {
  console.log(e);
  return fn(false);
 }); // Output directly to
 
 //catch cannot be guaranteed to be executed

If failures are not handled, errors will occur

fn(true) 
 .then(data => {
  console.log(data);
  return fn(false);
 })
 .catch(e=> {
  // Capture error
  console.log(e);
  return fn(false);
 })
 .finally( () => {
  console.log(100);
 });

Three states of Promise

Pending is in progress, fulfilled is successful, rejected is failed.State changes are irreversible. Once a resolution is changed, it cannot be modified (resolution, state changes to resolution). State can only be changed from pending to fulfilled, or from pending to rejected.

The Promise.all method wraps multiple promise instances into a new one

Promise.all( [promise1, promise2] ) : Promise

In the array, if promise s are all true, it returns true and the resolution is successful
 If one of the arrays is promise, false is returned and the resolution is failed

If it is an empty array, it returns true and the resolution succeeds

Model data for multiple requests

function getData1() {
 return new Promise((resolve, reject) => {
  setTimeout( () => {
   console.log('The first data was loaded successfully');
   resolve('data1');
  },1000);
 });
}

function getData2() {
 return new Promise((resolve, reject) => {
  setTimeout( () => {
   console.log('The second data was loaded successfully');
   resolve('data2');
  },1000);
 });
}

function getData3() {
 return new Promise((resolve, reject) => {
  setTimeout( () => {
   console.log('Article 3 Data Loaded Successfully');
   resolve('data3'); // Change to reject('err')
  },1000);
 });
}
let p = Promise.all( [getData1(), getData2(), getData3()] );

p.then(arr => {
 console.log(arr);
});

// fail

p.then(arr => {
 console.log(arr);
}, e => {
 console.log(e);
});

let p = Promise.all([]); // Resolution Success

p.then( () => {
 console.log(`da`);
}, e => {
 console.log(e);
});
The first data was loaded successfully
 The second data was loaded successfully
 Article 3 Data Loaded Successfully

Do not use Promise.all

let count = 0;
function getData1() {
 setTimeout( () => {
  console.log('The first data was loaded successfully');
  count ++;
  func();
  },1000);
}

function getData2() {
 setTimeout( () => {
  console.log('The second data was loaded successfully');
  count ++;
  func();
  },1000);
}

function getData3() {
 setTimeout( () => {
  console.log('Article 3 Data Loaded Successfully');
  count ++;
  func();
  },1000);
}

function getData4() {
 setTimeout( () => {
  console.log('Article 4 Successful data loading');
  count ++;
  func();
  },1000);
}

// Write a method:
function func() {
 if(count < 4)return;
 console.log('Get it all');
}

call

getData2();
getData3();
getData4();

let err = false;
function getData1() {
 setTimeout( () => {
  console.log('The first data was loaded successfully');
  if(status) err = true;
  count ++;
  func();
  },1000);
}

function func() {
 if(count < 4)return;
 console.log('Get it all');

 if(err) {
  // ...
 }
}

Promise.race()

Promise.race([promise1, promise2]) : Promise
let p = Promise.race([getData1(), getData2(),getData3()]);

p.then (data=>{
 console.log(data);
})
let flag = false;
function func(data) {
 if(flag) return
 flag = true;
 console.log(data);
}

function getData1() {
 setTimeout(()=>{
  console.log("The first data was loaded successfully");
  func({name: 'da'});
 },500);
}

function getData2() {
 setTimeout( () => {
  console.log("The second data was loaded successfully");
  func({name: 'dada'});
 }, 1000);
}

getData1();
getData2();

//The first data was loaded successfully
{name: 'da'}
//The second data was loaded successfully

Promise.resolve and Promise.reject

Promise.resolve() and Promise.reject()

// Promise.resolve
//Pass a common value
let p1 = new Promise(resolve => {
 resolve('Success!');
});

let p2 = Promise.resolve('Success!');

// Pass in a promise instance
let pro = new Promise(resolve => {
 resolve('da');
});

let p = Promise.resolve(pro);

p.then(data => void console.log(data));
let obj = {
 then (cb) {
  console.log('da');
  da('dada');
 },
 method() {
  console.log('coding');
 }
}

// Immediate execution
Promise.resolve(obj).then(data => {
 console.log(data);
});

Promise asynchronous:

console.log(1);

let p = new Promise(resolve => {
 console.log(2);
 resolve();
 console.log(3);
});

console.log(4);

p.then(()=>{
 console.log(5);
});

console.log(6);

// 123465

Promise improves code maintenance and inversion control issues caused by traditional callbacks. Promise is asynchronous. If all receives an empty array, it will be immediately resolved as successful. If race receives an empty array, it will be suspended forever, capturing error problems indefinitely.

resove and reject methods:

If a normal value is received, it is immediately determined to be successful and populated with the value. If a promise instance is received, the promise instance is returned. If a thenable object is received, it is wrapped as a promise object and the object's then method is executed immediately. reject generates a promise with a resolution failure and passes the value directly.

JavaScript/ES6 Promise

JavaScript's Promise represents the result of an operation that has not yet yielded results, such as a network request operation, when we retrieve data from a data source, there is no way to determine when it will be able to return and receive a response.

Promise Provides Standards

doSomething()
 .then(doSomethingElse)
 .catch(handleError)
 .then(doMore)
 .then(doFinally)
 .catch(handleAnotherError)

Create Promise

A Promise is created using the Promise constructor and accepts two parameters resolve, reject


var promise = new Promise( function(resolve, reject) {
 // new Promise resolve() reject()
}

XMLHttpRequest Of promise Edition:

function get(url) {
 return new Promise(function(resolve, reject) {
  var req = new XMLHttpRequest();
  req.open('GET', url);
  req.onload = function() {
   if(req.status == 200) {
    resolve(req.response);
   }else{
    reject(Error(req.statusText));
   }
  };
  req.onerror = function() {
   reject(Error("Network Error"));
  };
   req.send();
  });
 }

Use Promise

get(url)
 .then(function(response) {
 },function(err) {
 })

Processing error:

get(url)
 .then(function(response){
 }, undefined)
 .then(undefined, function(err){
 })
get(url)
 .then(function(response){
 })
 .catch(function(err){
 })

Chain

get(url)
 .then(function(response){
  response = JSON.parse(response);
  var secondURL = response.data.url
  return get(secondURL);
 })
 .then(function(response){
  response = JSON.parse(response);
  var thirdURL = response.data.url
  return get(thirdURL);
 })
 .catch(function(err){
  handleError(err);
 });

Parallel Execution Promise

The Promise.all() method resolves to success if each promise array is made up, and to failure if any one of the promises in the array is made up.

Task 1, Task 2, Task 3,.Then() -> success task succeeded

ES6

The Promise object is used to represent the final state of an asynchronous operation and the value it returns.

Grammar:

new Promise(function (resolve, reject) {
});

Several states:

The pending initial state is neither a success nor a failure state; fulfilled means the operation completed successfully; rejected means the operation failed.

A Promise object in the pending state may trigger the filfilled state and pass a value to the state handling method of the response, or it may trigger the rejected failure state and pass the failure message.

Promise.all(iterable)

This method returns a new promise object, which in the itearable parameter triggers success only when all promise object resolutions within it succeed, otherwise how one of the promise object resolutions fails immediately triggers failure of the promise object.

The Promise.all method is often used to handle a collection of states for multiple promise objects.

Promise.race(iterable)

When any of the child promises in the iterable parameter is resolved successfully or fails, the parent promise returns either with the success or failure of the child promises.

Promise.reject(reason)

Returns a promise object with a status of failure, passing the given failure information to the corresponding processing method.

Promise.resolve(value)

Returns a promise object with a status of failure, passing the given failure information to the corresponding processing method.

const myPromise = new Promise( (resolve, reject) => {
 resolve('resolve'); // filfilled
 reject('reject'); // rejected
});
function myFunction(url) {
 return new Promise( (resolve, reject) => {
  xhr.open ("GET", url);
  xhr.onload = () => resolve(xhr.responseText);
  xhr.onerror = () => reject(xhr.statusText);
  xhr.send();
 });
};

resolve() is called when asynchronous code execution succeeds and reject() is called when asynchronous code execution fails.

Simulate asynchronous code:

setTimeout(function(){
 resolve('Success');
},250);
});

myPromise.then(function(successMsg){
});

ES6 Promise Object

Promise objects are a solution to asynchronous programming, and syntactically, Promise is an object from which information about asynchronous operations can be obtained.

Promise state, promise asynchronous operation has three states, pending (in progress), fulfilled (succeeded), reject (failed).Except as a result of an asynchronous operation, no other operation can change this state.

const p1 = new Promise(function(resolve,reject){
    resolve('success1');
    resolve('success2');
}); 

const p2 = new Promise(function(resolve,reject){  
    resolve('success3'); 
    reject('reject');
});

p1.then(function(value){  
    console.log(value); // success1
});

p2.then(function(value){ 
    console.log(value); // success3
});

The disadvantage is that once a Promise is established, it will execute immediately and cannot be canceled halfway. If a callback function is not set, an error will be thrown inside the Promise and it will not be reflected externally.

The then method, which takes two functions as parameters.

The first parameter is the callback when Promise executes successfully, the second parameter is the callback when Promise fails, and only one of the two functions is called.

const p = new Promise(function(resolve,reject){
  resolve('success');
});
 
p.then(function(value){
  console.log(value);
});
 
console.log('first');
// first
// success
const p = new Promise(function(resolve,reject){
  resolve(1);
}).then(function(value){ // First then // 1
  console.log(value);
  return value * 2;
}).then(function(value){ // Second then // 2
  console.log(value);
}).then(function(value){ // Third then // undefined
  console.log(value);
  return Promise.resolve('resolve'); 
}).then(function(value){ // Fourth then // resolve
  console.log(value);
  return Promise.reject('reject'); 
}).then(function(value){ // Fifth then //reject:reject
  console.log('resolve:' + value);
}, function(err) {
  console.log('reject:' + err);
});

The then method returns a Promise object in the resolved or rejected state for chain calls.

Hot Promise

In JavaScript, all code is single-threaded, that is, executed synchronously, and promise is asynchronous programming that provides a solution.

The promise feature is that only asynchronous operations can determine the current state, and no other operation can change it; once the state changes, it does not change.

The process of state change: from pending to fulfilled and from pending to rejected. When the state changes, it does not change. This is called stereotyped resolved

Usage:

Promise objects are created by the keyword new and its constructor.


const promise = new Promise((resolve, reject) => {
    // do something here ...
    if (success) {
        resolve(value); // fulfilled
    } else {
        reject(error); // rejected
    }
}); 

The function receives two functions as parameters, resolve and reject. When the asynchronous operation succeeds, it passes the result of the asynchronous operation as a parameter into the resolve function and executes, where the Promise state changes from pending to fulfilled, and failure passes the error of the asynchronous operation as a parameter into the reject function and executes, where the Promise object state changes from pending to R.Ejected.

With the then method, a callback function for the resolved and rejected States is specified.

  promise.then(function(value) {
      // success
  }, function(error) {
      // failure
  });

Promise.all(iterable), Iterable must be an object that can be iterated, such as Array

The return value is a new Promise instance.

var p1 = new Promise((resolve, reject) => { 
  setTimeout(resolve, 1000, 'one'); 
}); 
var p2 = new Promise((resolve, reject) => { 
  setTimeout(resolve, 2000, 'two'); 
});
var p3 = new Promise((resolve, reject) => {
  setTimeout(resolve, 3000, 'three');
});
var p4 = new Promise((resolve, reject) => {
  reject('p4 reject!');
});
var p5 = new Promise((resolve, reject) => {
  reject('p5 reject!');
});

Promise.all([p1, p2, p3, p4, p5]).then(values => { 
  console.log(values);
}, reason => {
  console.log(reason)
});

// p4 reject!

Promise.race(iterable), similarly, returns a new Promise instance.

The new instance state returned will be the first instance to change state. If it is not a Promise instance, use the Promise.resolve method first. If the incoming iteration is empty, the returned Promise will wait forever.

A Promise instance Return the instance unchanged;

var original = Promise.resolve('Second line');

var da = Promise.resolve(original);

da.then(function(value) {
  console.log('value: ' + value);
});

console.log('original === da ? ' + (original === da));

// "original === da ? true"
// "value: second line"

Following this thenable object, takes its final state;

let thenable = {
  then: function(resolve, reject) {
    resolve(41);
  }
}

let p = Promise.resolve(thenable);

p.then(function(value) {
  console.log(value);
})

 // 41

Directly takes the incoming parameter as the final result and returns a new Promise;

let p = Promsie.resolve(12);

p.then(function(number) {
  console.log(number);
})

// 12

Returns a Promise object directly in a resolved state

let p = Promsie.resovle();

p.then(function() {
  // do something 
})

Promise.prototype.then()

p.then(onResolve, onReject);

p.then(function(value) {
  }, function(reason) {
});

Promise.prototype. catch()

p.catch(onReject)

 p.catch(function(reason) {
 });

  // bad
promise
  .then(function(data) {
    // success
  }, function(err) {
    // error
  });

// good
promise
  .then(function(data) { 
    // success
  })
  .catch(function(err) {
    // error
  });

Promise.prototype. finally()

  p.finally(onFinally);

  p.finally(function() {
   
  })

The callback function does not accept any parameters

Promise is an object that represents an asynchronous operation with three states in progress, success and failure.Only the result of an asynchronous operation can determine the current state, and once promise is newly executed, it cannot be stopped halfway.

The Promise.all method is used to wrap multiple Promise instances into a new Promise instance.The.then callback will not be executed until all promise functions as parameters have been run.

//Previous callback
 Function 1(function(){
    //Code execution... (ajax1)
    
    Function 2(function(){
        //Code execution... (ajax2)
        
        Function 3(function(data3){
              //Code Execution... (ajax3)
        });
        ...
    });
});

//Promise callback method: Chain call, can build multiple callback functions.
promise().then().then()...catch()

//Create Promise Instance
let promise = new Promise( (resolve, reject) => {
    //Execute the appropriate code to call resolve or reject as appropriate
    ...
})

//Callback execution in promise's then method
promise.then(function(){
        //The first parameter is when resolve is returned
    },function(){
        //The second is when the callback returns reject
    }
}

Timer Call

const promise = new Promise(function(resolve, reject){
    setTimeout(resolve,1000);
})

promise.then(function(){
  console.log('resolve:Successful callback function')  
},function(){
  console.log('reject:Failed Callback Function')
})

Pass-through parameters:

const promise = new Promise((resolve, reject) => {
    setTimeout(reject,1000,'I am value value');
})

promise.then((value) => {
    console.log('resolve:' + value)
}).catch((value) => {
    console.log('reject:'+ value)
})

//First, a single value passed is invalid
const promise = new Promise((resolve, reject) => {
    setTimeout(resolve,1000,'Parameter 1','Parameter 2');
})

promise.then((value1,value2) => {
    console.log('value1:' + value1)     //value1: Parameter 1
    console.log('value2:' + value2)     //value2:undefined
}).catch((value) => {
    console.log(value)
})

//Second: Array passing values
const promise = new Promise((resolve, reject) => {
    setTimeout(resolve,1000,['Parameter 1','Parameter 2']);
})
promise.then((value1) => {
    console.log('value1:' + value1)     //value1: parameter 1, parameter 2
}).catch((value) => {
    console.log(value)
})

Promise.prototype.then method: chain operation

getJSON("/posts.json").then(function(json) {
  return json.post;
}).then(function(post) {
  // proceed
});

Promise.prototype.catch method: catch errors

getJSON("/posts.json").then(function(posts) {
}).catch(function(error) {
  console.log('An error has occurred!', error);
});

Promise.all method, Promise.race method

var p = Promise.all([p1,p2,p3]);

var p = Promise.race([p1,p2,p3]);

Don't forget to leave a footprint of your studies [favorite collection reviews]

Author Info:

[Author]: Jeskson

Original Public Number: Dada Front End Bistro.

[Reprint instructions]: Please explain the source of reprinting, thank you for your cooperation!~

About the current article content refers to the front-end, PHP knowledge points, if you are interested, you can pay attention to it. It is an honor to be discovered by you. It is really wise-eyed!Thank you for your attention. In the future, I hope to be able to support me silently, and I will try to write more excellent works.We grew up together, programmed from zero basics, and presented our small partners with easy-to-understand Web front-end domains, data structures and algorithms, and network principles.Share Web front-end related technical articles, tool resources, selected courses, hot spot information.

If there are inadequacies in this number (e.g. copyright or other issues), please contact us in time to make corrections, which will be dealt with at the first time.

Please compliment!Because your approval/encouragement is my greatest motivation to write!

Welcome to your attention Dada CSDN!

This is a quality, attitudinal blog

Tags: Front-end JSON P4 Javascript network

Posted on Tue, 26 Nov 2019 17:11:26 -0800 by mick_otoole