What is asynchrony?

Asynchronous: Operations have little relationship to each other, multiple operations are performed simultaneously, no interference between operations (you can proceed first and then go back), complex code

Synchronization: only one thing can be done at the same time. The next operation (from top to bottom) can be performed after the above data is completed. The code is simple

When is promise used?

  • Typically, when there is an asynchronous operation, use Promise to encapsulate the asynchronous operation
  • New -> constructor (1. Saves some state information 2. Executes the function passed in)
  • When a callback is passed in, two functions are passed: resolve and reject, which are themselves functions
  • Promise separates the network request from the final processing code

Promise all callback parameters

Resolve (value) – If the task completes successfully with the result value

Reject (error) – Error is the error object if an error occurs.

The resolve function is called when the asynchronous task completes successfully and the result value is returned. The Reject function is called when the asynchronous task fails and returns the cause of the failure (usually an error object)

Promise.then () is called successfully

Promise.catch () failed call (this is a bit like a try.. If you don’t understand, you can click on the blue word to see it.

Promise.finally () is called on success and failure

The assignment writing

let promise = new Promise(function(resolve, reject) {
  setTimeout(() = > resolve("Dong!"), 1000);
});
 
// resolve runs the first function in.then
promise.then(
  result= > alert(result), // After 1 second "thunk!"
  error= > alert(error) / / is not running
);
 
/ / or
promise.then(alert); // After 1 second "thunk!"
Copy the code

As you can see, then takes two arguments:

The first argument to.then is a function that will run after Resolved and receive the result.

The second argument to.then is also a function that runs after Rejected and receives an error.

Chain calls

Execute side by side from top to bottom

new Promise(function(resolve, reject) {
  setTimeout(() = > resolve(1), 1000); 
}).then(function(result) { 
  alert(result); / / print 1
  return result * 2;
}).then(function(result) { 
  alert(result); / / print 2
  return result * 2;
})
Copy the code

promise.all

Promise. all This method returns a new promise object that will succeed only if all of the promise objects in the iterable argument object succeed, or fail

Common skills:

let urls = [
  'https://api.github.com/1'.'https://api.github.com/2'.'https://api.github.com/3'
];
 
// Map each URL into the fetch's promise
let requests = urls.map(url= > fetch(url));
 
// Promise. All will wait until all tasks are resolved
Promise.all(requests)
  .then(responses= > console.log(responses)
  ));
// Outputs the array of links
//[https://api.github.com/1,https://api.github.com/2,https://api.github.com/3]
Copy the code

Return a promise in the function

function promisify(f) {
    return new Promise((resolve, reject) = > {
        if (err) {
          reject(err);
        } else{ resolve(result); }})}/ / usage:
letPromises = promisify(parameters); Promises(...) .then(...) ;Copy the code

Attached is the MDN diagram:

Use ajax web requests in conjunction with promises:

function createPromise(url) {
      // resolve successfully reject failure
      return new Promise(function (resolve, reject) {
        $.ajax({
          / / es6 shorthand
          url,
          dataType: 'json'.success(arr) {
            resolve(arr);
          },
          error(err) {
            reject(err)
          },
        })
      });
    }
   
    // Return success
    Promise.all([
      createPromise('./arr.txt'),
      createPromise('./json.txt')
      Then (function(){},function(){}), function(){})
    ]).then(function (arr) {  
      // Destruct the assignment
      // res1 is the first link and res2 is the second link
      let [res1, res2] = arr;
 
      alert('All success');
      alert(res1);
      alert(res2);
    }, function () {
      alert('At least one of them failed.')}/* Then has two arguments the first argument is a function that will run after resolved and receive the result. The second argument is also a function that will run after Rejected and receive error. * /
Copy the code

Microtask queues in asynchrony

Tasks in the task queue are not executed until they are finished in the JavaScript engine.

Queues are also executed in order, with the first task to be queued running first.

When a promise is ready, its then/catch/finally handlers are queued: but they are not executed immediately. When the JavaScript engine finishes executing the current code, it grabs the task from the queue and executes it.

The following code executes the synchronization code first:

1.  let promise = Promise.resolve();
1.
1.  promise.then(() = > alert("2"));
1.
1.  alert("1"); // The 1 is displayed first
Copy the code

If we need to ensure that a piece of code is executed after asynchrony, we can add it to the.then of the chain call

Finally, choose a way you like to write, I was a little blind at the beginning, in fact, just to introduce promise from all angles, after I have a general understanding, it will be more convenient to use

  • The public account: honest front end person, we can chat and exchange learning together!