zoukankan      html  css  js  c++  java
  • [Javascript] Convert a Callback-Based JavaScript Function to a Promise-Based One

    Sometimes, you might want to convert a JavaScript function that accepts a callback to one that returns a Promiseobject. This lesson shows how to manually wrap a promise-based API around the fs.readFile() function. It also explains how to use the util.promisify() method that is built into the Node.js standard library.

     
    const fs = require('fs')
    
    function readFile(path, encoding) {
      return new Promise((resolve, reject) => {
        fs.readFile(path, encoding, (error, contents) => {
          if (error) {
            reject(error)
          } else {
            resolve(contents)
          }
        })
      })
    }
    
    readFile(__filename, "utf8")
    .then((contents) => {
      console.log(contents)
    }, error => {
      console.error(error)
    })

    In nodejs we can use util function:

    const fs = require("fs");
    const util = require("util");
    
    const readFile = util.promisify(fs.readFile);
    
    readFile(__filename, "utf8").then(
      contents => {
        console.log(contents);
      },
      error => {
        console.error(error);
      }
    );
  • 相关阅读:
    第五周作业
    第四周作业
    第三周作业(两个题)
    第六周作业
    第五周作业
    第四周作业
    第三周作业
    第二周作业
    求最大值及其下标
    查找整数
  • 原文地址:https://www.cnblogs.com/Answer1215/p/10084591.html
Copyright © 2011-2022 走看看