This article may be the only difference between you and understanding promise (1)

Time:2019-12-23

Let me see~

Before promise:

Because the JS engine allocates only one thread to execute JS code, JavaScript is single threaded. Because of this pre setting, one of the things that front-end Er can’t get around when writing code is how to deal with asynchrony, that is, how to deal with the “now and later” relationship. In fact, we are dealing with asynchronous logic every day.

Before promise appeared, the front-end Er basically solved the “later” problem through the way of callback, such as the classic “publish subscribe” mode, observer mode, they all used the high-order function of the incoming callback function. The vue2. X source code is the publish – Subscribe mode when it realizes data bidirectional binding.

Let’s look at three examples first. (the examples are all running in the node environment, where the content in name.txt is “KK”, and the content in age.txt is 10.)

1. Callback function. The order of FS reading files is not fixed. We can’t judge which file is read first. This example implements an operation (such as console) after reading the contents of two files completely.

let fs = require('fs');

let arr = [];
let after = (times, cb) => {
 return (data) => {
 arr.push(data);
 if (--times === 0) {
 cb(arr)
   }
 }
}

let on = after(2, (arr) => {
 Console. Log ('I printed it after reading all the contents of 2 files,'arr)
})
fs.readFile('name.txt', 'utf8', (err, data) => {
 on(data)
})

fs.readFile('age.txt', 'utf8', (err, data) => {
 on(data)
})

Result:
  I printed it after reading all the contents of two files, ['kk ','10'].

Explain:
  The problem with this writing method is that it relies on counting to execute the contents of the callback function. We need to figure out how many asynchronous operations there are, and then count them and execute the callback after all asynchronous operations are completed.

2. Publish subscribe mode. Add subscribers when subscribing, and execute corresponding subscription functions when publishing. In this example, an event is exited at a specific time, and the callback function that subscribes to the event is executed.

class EventEmitter {
  constructor () {
    this.subs = {}
  }
  on (eventName, cb) {
    if (!this.subs[eventName]) {
      this.subs[eventName] = []
    }
    this.subs[eventName].push((...args) => cb(...args))
  }
  emit (eventName, ...args) {
    if (this.subs[eventName]) {
       this.subs[eventName].forEach(cb => cb(...args))
    } else {
        Throw error (` no subscription to ${eventName} this event ')
    }
   }
}

const event = new EventEmitter();
let fs = require('fs');
event.on('kk-event', (...args) => {
  fs.readFile('name.txt', 'utf8', (err, data) => {
    console.log('data1', data, ...args)
  })
})
event.on('kk-event', (...args) => {
  fs.readFile('age.txt', 'utf8', (err, data) => {
    console.log('data2', data, ...args)
  })
})
event.emit('kk-event', 123, 456)

Result:

data1 kk 123 456
data2 10 123 456

3. Observer mode. It is essentially the same as publish subscribe, except that the observer mode emphasizes the relationship between the observer and the observed in writing, while publish subscribe mode has no such relationship. In this example, after the state of the observed changes, the observer performs its own update method to update.

class Subject {
  constructor() {
    this.observers = [];
    This. State = '; // suppose the observer observes the state of the observed
  }
  Setstate (status) {// the update method of the starting observer when the state changes
    this.state = status;
    this.notify();
  }
  attach (observer) {
    This. Observers. Push (observer) // different from publish subscribe, here are observer instances, which associate the observed with the observer
  }
  notify () {
    This. Observers. Foreach (observe = > observe. Update()) // when the state of the observed changes, the observer's update method is called to update
  }
}

class Observer {
  constructor (name, target) {
    this.name = name;
    this.target = target;
  }
  update () {
    Console. Log (` notify ${this. Name}, the state of the observed changes, so the observer ${this. Name} changes with it ')
  }
}

let fs = require('fs');
let subject = new Subject();
let observer1 = new Observer('kk1', subject);
let observer2 = new Observer('kk2', subject);
subject.attach(observer1);
subject.attach(observer2);
subject.setState('B');

Result:

Notice KK1, the state of the observed changes, so the observer KK1 changes with it
Notice KK2, the state of the observed changes, so the observer KK2 changes with it

Recommended Today

Analysis of new data type instances of ES6 learning notes

An example of this paper describes the new data types of ES6 learning notes. To share with you for your reference, as follows: 1. Data deconstruction assignment 1. Deconstruction and assignment of arrays Basic usage: let [key1, key2…] = [value1, Value2…] Let [name, age, sex] = [‘xiaoming ‘, 24,’ male ‘]; console.log(name); console.log(age); console.log(sex); Note […]