• [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);
      }
    );
  • 相关阅读:
    bus总线
    vue 动态组件、父子组件传参
    echarts
    记录板
    留言板
    如何移除双系统mac中的windows系统
    Kernel,Shell,Bash 的关系
    zju 校队选拔 被虐记
    COGS 2638. 数列操作ψ 线段树
    退役公告【现已复活】
  • 原文地址:https://www.cnblogs.com/Answer1215/p/10084591.html
Copyright © 2020-2023  润新知