Home  >  Article  >  Web Front-end  >  Learn more about Promise objects in Nodejs

Learn more about Promise objects in Nodejs

青灯夜游
青灯夜游forward
2021-03-30 18:44:341992browse

This article will take you through the Promise object in Nodejs. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

Learn more about Promise objects in Nodejs

Related recommendations: "nodejs Tutorial"

Promise Object

1. What is promise used for?

Our requirement is to execute the asynchronous code once

Our approach is in the callback function after the asynchronous request is successful , execute the next asynchronous request

But this will cause callback hell (the callback function is nested in the callback function, the readability of the code is low, the maintenance is unchanged, and it is scary to look at) )

promise is used to solve callback hell

Example of callback hell:

// 需求:一次的读取a,b,c这三个文件
const fs = require("fs");

// 读a文件
fs.readFile(`${__dirname}/etc/a.txt`, "utf-8", (err, data) => {
  if (err) {
    console.log(err);
  } else {
    console.log(data);
    // 读b文件
    fs.readFile(`${__dirname}/etc/b.txt`, "utf-8", (err, data) => {
      if (err) {
        console.log(err);
      } else {
        console.log(data);
        // 读c文件
        fs.readFile(`${__dirname}/etc/c.txt`, "utf-8", (err, data) => {
          if (err) {
            console.log(err);
          } else {
            console.log(data);
          }
        });
      }
    });
  }
});

2. Promise workflow

es6 syntax, es6.ruanyifeng.com

The Promise object is a constructor , used to generate promise instances

The Promise constructor accepts a function as a parameter

This function as a parameter has two parameters, These two parameters are resolve and reject

These two parameters are also functions, but these two functions are provided by the javascript engine, so you don’t need to deploy them yourself

The resolve() method is called after the asynchronous operation is successful. It internally calls the first parameter function in then()

The reject() method is called after the asynchronous operation is successful. , he internally calls the second parameter function in then().

const fs = require("fs");
// 调用Promise构造函数,创建一个promise的实例
let p = new Promise((resolve, reject) => {
  // 写异步操作(读文件)
  fs.readFile(`${__dirname}/etc/a.txt`, "utf-8", (err, data) => {
    if (!err) {
      // 操作成功(读文件成功)
      resolve(data); // 调用resolve方法
      // 调用then()里面的第一个参数函数
    } else {
      reject(err); // 调用reject方法
      // 调用then()里面的第二个参数函数
    }
  });
});

p.then(
  (data) => {
    console.log(data);
  },
  (err) => {
    console.log(err);
  }
);

3. Promise principle

Promise object represents an asynchronous operation.

There are three states: pending (in progress), fulfilled (successful) and rejected (failed)

There are only two possibilities for the state of the Promise object to change: from pending to fulfilled and from pending to rejected.

Only the result of asynchronous operation can determine the current state, and no other operation can change this state

If asynchronous operation If it succeeds (reading the file successfully), it changes from pending (in progress) to fulfilled (successful);

If the asynchronous operation fails (reading the file fails), it changes from pending ( In progress) becomes rejected (failed);

If the status has been determined, it will not be changed again

4. Promise characteristics and encapsulation

Promise will be executed immediately after it is created

So don’t write it in promise For other codes, just write the code for this asynchronous operation

const fs = require("fs");
function getPromise(filename) {
  // 调用Promise构造函数,创建一个promise的实例
  return new Promise((resolve, reject) => {
    // 写异步操作(读文件)
    fs.readFile(`${__dirname}/etc/${filename}.txt`, "utf-8", (err, data) => {
      if (!err) {
        // 操作成功(读文件成功)
        resolve(data); // 调用resolve方法
        // 调用then()里面的第一个参数函数
      } else {
        reject(err); // 调用reject方法
        // 调用then()里面的第二个参数函数
      }
    });
  });
}

// console.log(getPromise("a"));
getPromise("a").then(
  (data) => {
    console.log(data);
  },
  (err) => {
    console.log(err);
  }
);

5. Correct way to write promise

How promise solves callback hell

-》Chain programming solves

**The problem we use promise to solve: let asynchronous operations have order, and there can be no Callback hell**

The essence of making asynchronous operations sequential is:

Asynchronous operations are actually unsequential

Return another promise in the callback function after the asynchronous operation is successful and call its then method

const fs = require("fs");
function getPromise(filename) {
  // 调用Promise构造函数,创建一个promise的实例
  return new Promise((resolve, reject) => {
    // 写异步操作(读文件)
    fs.readFile(`${__dirname}/etc/${filename}.txt`, "utf-8", (err, data) => {
      if (!err) {
        // 操作成功(读文件成功)
        resolve(data); // 调用resolve方法
        // 调用then()里面的第一个参数函数
      } else {
        reject(err); // 调用reject方法
        // 调用then()里面的第二个参数函数
      }
    });
  });
}

// console.log(getPromise("a"));
getPromise("a")
  .then((data) => {
    console.log(data);
    //调用函数得到一个读b文件的promise对象并返回
    return getPromise("b");
  })
  .then((data) => {
    console.log(data);
    //调用函数得到一个读c文件的promise对象并返回
    return getPromise("c");
  })
  .then((data) => {
    console.log(data);
  });

6. Other methods of promise

  • catch()

    can catch the wrong

    const fs = require("fs");
    function getPromise(filename) {
      // 调用Promise构造函数,创建一个promise的实例
      return new Promise((resolve, reject) => {
        // 写异步操作(读文件)
        fs.readFile(`${__dirname}/etc/${filename}.txt`, "utf-8", (err, data) => {
          if (!err) {
            // 操作成功(读文件成功)
            resolve(data); // 调用resolve方法
            // 调用then()里面的第一个参数函数
          } else {
            reject(err); // 调用reject方法
            // 调用then()里面的第二个参数函数
          }
        });
      });
    }
    
    // console.log(getPromise("a"));
    getPromise("a")
      .then((data) => {
        console.log(data);
        //调用函数得到一个读b文件的promise对象并返回
        return getPromise("b");
      })
      .then((data) => {
        console.log(data);
        //调用函数得到一个读c文件的promise对象并返回
        return getPromise("c");
      })
      .then((data) => {
        console.log(data);
      })
      .catch((err) => {
        console.log(err);
      });
  • all()

    const fs = require("fs");
    function getPromise(filename) {
      // 调用Promise构造函数,创建一个promise的实例
      return new Promise((resolve, reject) => {
        // 写异步操作(读文件)
        fs.readFile(`${__dirname}/etc/${filename}.txt`, "utf-8", (err, data) => {
          if (!err) {
            // 操作成功(读文件成功)
            resolve(data); // 调用resolve方法
            // 调用then()里面的第一个参数函数
          } else {
            reject(err); // 调用reject方法
            // 调用then()里面的第二个参数函数
          }
        });
      });
    }
    
    let p1 = getPromise("a");
    let p2 = getPromise("b");
    let p3 = getPromise("c");
    
    // Promise.all()方法用于将多个 Promise 实例,包装成一个新的 Promise 实例
    let pAll = Promise.all([p1, p2, p3]);
    // 一个都不能少,每一个promise都要读取成功才会成功,相当于是并且
    pAll.then((data) => {
      console.log(data);
    });
  • race

    const fs = require("fs");
    function getPromise(filename) {
      // 调用Promise构造函数,创建一个promise的实例
      return new Promise((resolve, reject) => {
        // 写异步操作(读文件)
        fs.readFile(`${__dirname}/etc/${filename}.txt`, "utf-8", (err, data) => {
          if (!err) {
            // 操作成功(读文件成功)
            resolve(data); // 调用resolve方法
            // 调用then()里面的第一个参数函数
          } else {
            reject(err); // 调用reject方法
            // 调用then()里面的第二个参数函数
          }
        });
      });
    }
    
    let p1 = getPromise("a");
    let p2 = getPromise("b");
    let p3 = getPromise("c");
    
    // Promise.race()方法同样是将多个 Promise 实例,包装成一个新的 Promise 实例
    let pRace = Promise.race([p1, p2, p3]);
    // 只要有一个promise执行成功,那这个pRace就成功,相当于是或者
    pRace.then((data) => {
      console.log(data);
    });

More For more programming related knowledge, please visit: programming video! !

The above is the detailed content of Learn more about Promise objects in Nodejs. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete