directory

  • asynchronous
  • The callback
  • The relationship between asynchrony and callback
  • How to identify asynchrony
  • Promise

A, asynchronous

You can’t get the result directly, such as setTimeout. You can’t get the result until after the specified event.

Second, the callback

Write a function and not use it immediately, but give it to someone else to call.

  • The callback example

    In the following example, F1 is the callback

function f1(value) {
  console.log("I'm a formula one." + value);
}
function f2(fn) {
  fn("I'm F2. I called F1.");
}
f2(f1);
Copy the code

Asynchrony and callback

  • associated

    Asynchronous tasks need to notify JS to get the results when they get them. But how?

Write a function to the browser that the browser calls when the asynchronous task completes. The result is also passed to the function as an argument. This function is also called the callback function.

  • The difference between

Asynchronous tasks require callback functions to retrieve notification results

However, callbacks do not have to be used only for asynchronous tasks. Callbacks can also be used for synchronous tasks. For example, array.foreach (n=>console.log(n)) is a synchronization callback.

How to judge asynchrony

  • asynchronous
    1. setTimeout
    2. AJAX (i.e., the XMLHttpRequest)
    3. addEventListener
    4. More asynchronous subsequent updates

Five, the Promise

  • Why do we have promises?
    1. Unified solution for asynchronous programming
    2. Used when an asynchronous task has two results (success or failure)
    3. Specify the names and order of callbacks
    4. Easy to catch errors
    5. avoidThe callback hell

  • The state of the Promise
    1. Pending: Initial state, that is, no cash, no rejection
    2. This is a big pity.: Indicates that the operation is complete
    3. I have rejected the offer.: Means failure

This is a big pity. The Promise object in the pending state will either be fulfilled through a value, or will be rejected through a reason (mistake). When one of these conditions occurs, our associated handlers, arrayed with the promise’s then methods, are called. If a promise has already been fulfilled or rejected by the time a corresponding handler is bound, the handler is invoked, so there is no state of contention between completing the asynchronous operation and the binding handler.

  • The pose Promise used
// It is used for encapsulation
const fn = function f1() {
  return new Promise((resolve, reject) = > {
    // Do some asynchronous operations
    ifResolve (someValue); }else if{reject(elseValue); }}); };// Used when creating a Promise instance object
const xxx = new Promise((resolve, reject) = > {});
Then (success,fail) is passed to call the successful and failed functions
xxx.then(success_fn, fail_fn);
// Use catch to catch errors
xxx.catch((err) = > {
  console.log("Error cause:" + err);
});
Copy the code
  • Use Promise to encapsulate Ajax easily
const ajax = (method, url, options) = > {
  return new Promise((resolve, reject) = > {
    const { success, fail } = options;
    const request = new XMLHttpRequest();
    request.open(method, url);
    request.onreadystatechange = () = > {
      if (request.readyState === 4) {
        if (request.status < 400) {
          resolve(request.response);
        } else if (request.status > 400) { reject(request); }}}; request.send(); }); };// Use wrapped Ajax
ajax("GET"."/xxx").then(
  (response) = > {},
  (request) = >{});Copy the code
  • summary
  1. return new Promise((resolve,reject)=>{})
  2. Resolve (result) if the task succeeds, reject(error) if the task fails
  3. Resolve and reject call success and failure functions
  4. Pass in the success and failure functions using. Then (success,fail)
  5. Catch ((err)=>{}) to catch an error