Review promise — node

Time:2020-3-25

I don’t know how many times I’ve seen promise! It’s very important to recall

discover problems

const fs = require('fs')

fs.readFile('./data/1.txt', (err, data) => {
  console.log(111)
  fs.readFile('./data/2.txt', (err, data) => {
    console.log(222)
    fs.readFile('./data/3.txt', (err, data) => {
      console.log(333)
    })
  })
})

// Promise

Using promise

/**
 *Promise is an object in ECMAScript 6
 *Promise is a container
 *Generally used to encapsulate an asynchronous operation
 *Asynchronous operation is an unpredictable thing. Do you want to succeed or fail
 *There are three states inside the container:
 *Pending processing
 *Resolved successfully, resolved
 *Rejected, failed
 */

const fs = require('fs')

//Promise objects are executed as soon as they are created
new Promise((resolve, reject) => {
  fs.readFile('./data/2.txt', (err, data) => {
    if (err) {
      //When the result of the asynchronous operation inside the promise object fails, tell the promise object container that the asynchronous task fails
      //In fact, change the pending state in project to rejected
      reject(err)
    }
    //When the code is executed here, it indicates that there is no error in the asynchronous operation within the promise object, which proves the success
    //Then change the pending state in promise to resolved
    resolve(data)
  })
})
//Promise instance object has a method: then method
//Then you need to pass two callback handlers
//The first callback handler is the resolve function inside the promise object
//The second callback handler is optional. If it is passed, it is the reject function inside the project object
.then((data) => {
  console.log(111)
  console.log(data.toString())
  return new Promise((resolve, reject) => {
    fs.readFile('./data/3.txt', (err, data) => {
      if (err) {
        //The reason why return is not used here is that the project status can only change from pending to resolved or rejected
        //Once the state changes, it will not change again
        reject(err)
      }
      resolve(data)
    })
  })
}, (err) => {
  Console. Log ('failed to read file ')
})
//After the then method, you can continue to chain call then
//The callback handler specified in each subsequent then is executed
//The callback handler specified in the subsequent then can receive the return result of the successful callback handler specified in the previous then
//1. No return value, default is undefined
//2. There are common return values, numbers, strings, objects, arrays...
//3. Return a new promise object
.then((data) => {
  console.log(222)
  console.log(data.toString())
  return new Promise((resolve, reject) => {
    fs.readFile('./data/1.txt', (err, data) => {
      if (err) {
        //The reason why return is not used here is that the project status can only change from pending to resolved or rejected
        //Once the state changes, it will not change again
        reject(err)
      }
      resolve(data)
    })
  })
})
.then((data) => {
  console.log(333)
  //The binary data call tostring() method can be converted to normal characters, and the default is utf8 encoding
  console.log(data.toString())
})

Package promise

const fs = require('fs')

readFile('./data/1.txt', 'utf8')
  .then(data => {
    console.log(data)
    return readFile('./data/2.txt', 'utf8')
  })
  .then(data => {
    console.log(data)
    return readFile('./data/3.txt', 'utf8')
  })
  .then(data => {
    console.log(data)
  })

function readFile(...args) {
  return new Promise((resolve, reject) => {
    fs.readFile(...args, (err, data) => {
      if (err) {
        reject(err)
      }
      resolve(data)
    })
  })
}

Promise in HTML page

XMLHttpRequest - Promise


  
    Full name:
    Age:
  
  

    function xhr(options) {
      return new Promise(function (resolve, reject) {
        var xhr = new XMLHttpRequest()
        xhr.open(options.type || 'get', options.url)
        xhr.onreadystatechange = function () {
          if (xhr.readyState === 4 && xhr.status === 200) {
            resolve(xhr.responseText)
          } else {
            reject()
          }
        }
        xhr.send()
      })
    }

    xhr({
      url: '',
      type: '',
      data: ''
    })
    .then(data => {
      return xhr({
        
      })
    })
    .then(data => {
      //Rendering
    })

    $.ajax({

    }).then(data => {
      return $.ajax({

      })
    })
    .then(data => {
      
    })

Handling errors – last

This kind of thing puts mistakes at the end
Of course, you can also handle errors in the middle
But it’s usually at the end of the day

const fs = require('fs')

readFile('./data/4.txt', 'utf8')
  .then(data => {
    console.log(data)
    return readFile('./data/2.txt', 'utf8')
  })
  .then(data => {
    console.log(data)
    JSON.parse('{dsadsa')
    return readFile('./data/3.txt', 'utf8')
  })
  .then(data => {
    console.log(data)
  })
  //When using promise for asynchronous process control, exception handling can be done by setting a catch after the last then
  //Then specify a failure handling function
  //This function can catch all the previous promise objects and task errors inside them
  //When any of the previous exceptions occur, enter the catch directly, and all subsequent promises, including then, will not be executed
  .catch(err => {
    console.log(err)
  })

function readFile(...args) {
  return new Promise((resolve, reject) => {
    fs.readFile(...args, (err, data) => {
      if (err) {
        reject(err)
      }
      resolve(data)
    })
  })
}

Promise resolve does not support multiple parameters