1,

Promise is a solution to asynchronous programming that is more reasonable and powerful than callback functions and events. Think of it as a container that holds the result of an event that will end in the future.

2, the characteristics of

  • A Promise object has three states: Pending, fulfilled and Rejected. This state is not affected by the outside world.

  • The state can change from Pending to depressing or from Pending to Rejected. Once the state changes, it never changes.

3, the disadvantages

  • Once a Promise is created, it executes immediately and cannot be canceled

  • If the callback function is not set, errors thrown inside a Promise are not reflected outside

  • When in the Pending state, there is no way to know whether the current progress has just begun or is about to be completed

4. Basic usage

ES6 states that a Promise object is a constructor that generates a Promise instance. It takes a function as arguments: resolve and Reject. Resolve changes the state of the Promise object from incomplete to successful. The Reject function changes the never-complete state of a Promise object to a failure.

const promise = new Promise(function(resolve, reject) {
  if (/* Asynchronous operation succeeded */){
    resolve(value);
  } else{ reject(error); }});Copy the code

5, then

After a Promise instance is generated, the then method can be used to specify the callback in the Resolved state and rejected state respectively. Generally, the first parameter is used, while the reject state is handled by catch.

function timeout(ms) {
  return new Promise((resolve, reject) = > {
    setTimeout(resolve('done'), ms);
  });
}

timeout(100).then(
	/ / resolve the callback
  (value) = > { console.log(value) },
  / / reject callback
  (error) = > { console.log(error) }
);
Copy the code

Promise is executed as soon as it is created, but the THEN method is a microtask and will not be executed until all synchronization tasks in the current script have been executed. The following code: the first output is A. Then is the callback specified by the then method, so B prints last.

let promise = new Promise(function(resolve, reject) {
  console.log('A');
  resolve();
});

promise.then(function() {
  console.log('B');
});

console.log('C');

// Output sequence A, C, B
Copy the code

The then method returns a new Promise instance (not the original Promise instance). So you can write it chained, where a then method is followed by another THEN method.

getJSON("/api")
.then(post= > getJSON(post.commentURL))
.then(comments= > console.log("resolve", comments))
Copy the code

The result of the p2 operation returns the result of the p1 asynchronous operation. So p1’s state is going to be transferred to P2, which means that p1’s state determines P2’s state. If P1’s state is pending, p2’s callback waits for p1’s state to change. If P1 is in resolved or Rejected, the P2 callback will be executed immediately.

const p1 = new Promise(function (resolve, reject) {
  setTimeout(() = > reject(new Error('fail')), 3000)})const p2 = new Promise(function (resolve, reject) {
  setTimeout(() = > resolve(p1), 1000)
})

p2
  .then(result= > console.log(result))
  .catch(error= > console.log(error))
Copy the code

6, catch

Like then, the catch() method returns a Promise object, so the then() method can be called later, and if no error is reported, the catch() method will be skipped. Catch (); catch(); catch()

const someAsyncThing = function() {
  return new Promise(function(resolve, reject) {
    // The next line is an error because x is not declared
    resolve(x + 2);
  });
};

someAsyncThing()
.catch(function(error) {
  console.log('oh no', error);
})
.then(function() {
  console.log('carry on');
});
Copy the code

7, the finally

The finally() method was introduced as a standard in ES2018. Used to specify actions that will be performed regardless of the final state of the Promise object. This method always returns the original value and does not accept any parameters, which means there is no way to know whether the Promise state is fulfilled or Rejected.

promise
.then(result= >{...}). The catch (error= >{...}). Finally,() = > {···});
Copy the code

8, all ()

The promise.all () method is used to wrap multiple Promise instances into a new Promise instance. This method takes an array as an argument (it may not be an array, but it must have an Iterator interface, and each member returned is a Promise instance).

const p = Promise.all([p1, p2, p3]);
Copy the code

As shown in the code above, p1, P2, and p3 are all Promise instances. If not, promise.resolve () is called first, and the argument is converted to a Promise instance.

Note:

  • Promise.all() does not complete until all the promises in the array are completed

  • If one of the promises in the array fails, promise.all () will fail, and the first failed Promise instance is passed to the promise.all () callback

  • If a Promise instance that is a parameter defines its own catch method, then it does not fire the promise.all () catch method once it is rejected.

9, race ()

The promise.race () method also wraps multiple Promise instances into a new Promise instance with the same parameters as the promise.all () method.

const p = Promise.race([p1, p2, p3]);
Copy the code

Race means speed, and as it literally means, whoever is fast takes the result. In the above code, the state of P changes as long as one of the first instances of P1, P2, and P3 changes state. The return value of the first changed Promise instance is passed to p’s callback function.

10, allSettled ()

The promise.allSettled () method takes an array as an argument, each member of which is a Promise object, and returns a new set of Promise arrays.

Note: The returned Promise will change its state only after all the Promise objects in the parameter array have state changes (whether this is a pity or Rejected).

const p1 = new Promise((resolve, reject) = > {
  setTimeout(() = > {
    resolve('ok')},1000)})const p2 = new Promise((resolve, reject) = > {
  setTimeout(() = > {
    reject('no')},2000)})const p3 = new Promise((resolve, reject) = > {
  setTimeout(() = > {
    resolve('ok')},3000)})const all = Promise.allSettled([p1, p2, p3])
.then(res= > {
  console.log(res)
})
Copy the code

11, any ()

The promise.any () method takes an array, each member of which is a Promise object, and returns a new set of Promise arrays.

Note: As long as one of the Promise objects in the parameter array becomes the fulfilled state, promise.any () will become the fulfilled state. Promise.any() becomes the Rejected state only if all the Promise objects in the parameter array become the Rejected state.

const all = Promise.any([p1, p2, p3])
.then(res= > {
 	console.log(res)
})
.catch(err= > {
	console.log(err)
})
Copy the code

12. Existing objects become Promise objects

Sometimes you need to turn an existing object into a Promise object. Promise.resolve() and promise.reject () do this.

onst p = Promise.resolve('Hello');

p.then(function (s) {
  console.log(s)
});
Hello / / output
Copy the code

or

Promise.reject('Wrong')
.catch(e= > {
  console.log(e)
})
// Output error
Copy the code

13. Practical usage

Here are a few simple examples that have many uses.

13.1, Applets request

const Request = (options) = >{
  let url = baseURL + options.url;
  return new Promise((resolve, reject) = > {
    wx.request({
      url,
      data: options.data || {},
      method: options.method || 'post'.responseType: options.responseType || ' '.timeout: 15000,
      success (res) {
        if(res.statusCode === 200){
          resolve(res.data);
        }else{
          FN.Toast(res.errMsg);
        };
      },
      fail (res) {
        FN.Toast("The network has wandered off."); reject(res); }})})}Copy the code

13.2, Picture loading

const preloadImage = function (path) {
  return new Promise(function (resolve, reject) {
    const image = new Image();
    image.onload  = resolve;
    image.onerror = reject;
    image.src = path;
  });
}
Copy the code

13.3. Encapsulate Toast

import { Message, MessageBox} from 'element-ui'

/** * Prompt box *@param {String} text* /
alert(text) {
  return new Promise((resolve, reject) = > {
    MessageBox.alert(text, 'Warm reminder', {
      confirmButtonText: 'sure'.callback: action= > {
		if (action === 'confirm'){
			resolve(action)
		} else {
			reject(action)
		}
      }
    })
  })
}
Copy the code

If you think it is helpful, I am @pengduo, welcome to like and follow the comments; END

The articles

  • Use NVM to manage node.js version and change NPM Taobao image source
  • More detailed! Vue’s nine ways of communication
  • Wechat small program to achieve search keyword highlighting
  • Env files are used in vUE to store global environment variables and configure vUE startup and package commands
  • More detailed! Vuex hands-on tutorials

Personal home page

  • CSDN
  • GitHub
  • Jane’s book
  • Blog garden
  • The Denver nuggets