【源码共读】第14期 | 通过remote-git-tags学会promisify

1. 前言

2. remote-git-tags

remote-git-tags是用来获取远程仓库tag的库。 在学习这个之前,先来认识下promisify是什么?

3. promisify

promisify是一个可以将回调函数转换为Promise形式函数的工具。回调函数是最原始的异步处理方案,但使用它容易引发一些问题,如回调地狱和对异常错误的捕获不够方便等。

例如:现在使用node读取文件

回调写法

js 复制代码
fs.readFile("test.txt", function (err, data) {
  if (!err) {
    console.log('callback',data.toString());
  } else {
    console.log(err);
  }
});

promise写法

js 复制代码
const promiseRead = () => {
    return new Promise((resolve, reject) => {
      fs.readFile("test.txt", function (err, data) {
        if (!err) {
          resolve(data.toString());
        } else {
          reject(err);
        }
      });
    });
  };

promisify写法

js 复制代码
import { promisify } from "node:util";

 const fn = promisify(fs.readFile);
  fn("test.txt").then((res) => {
    console.log('promisify', res.toString());
  });

自实现promisify写法

js 复制代码
const selfPromisify = (original) => {
    return (...args) => {
      return new Promise((resolve, reject) => {
        args.push((err, ...values) => {
          if (err) {
            return reject(err);
          }
          resolve(values);
        });
        Reflect.apply(original, this, args);
      });
    };
  };

  const selfFn = promisify(fs.readFile);
  const res = await selfFn("test.txt");

结果如下:

4. remote-git-tags源码调试

js 复制代码
import {promisify} from 'node:util';
import childProcess from 'node:child_process';

const execFile = promisify(childProcess.execFile);

export default async function remoteGitTags(repoUrl) {
    const {stdout} = await execFile('git', ['ls-remote', '--tags', repoUrl]);
    const tags = new Map();

    for (const line of stdout.trim().split('\n')) {
        const [hash, tagReference] = line.split('\t');
        const tagName = tagReference.replace(/^refs\/tags\//, '').replace(/\^{}$/, '');

        tags.set(tagName, hash);
    }

    return tags;
}

运行步骤:

  1. 使用child_process.exec()执行命令,用promisify包裹,返回promsie
  2. 遍历版本和Hash放到一个Map对象中,使用两次替换,最终获得版本

执行命令的结果"bac3bd8ecf9beb7b1d8dfb596cb89a7fd898936b\trefs/tags/v1.0.0\ndeb487bbb4fa1a22bbe6462aa527b2bcf0248f02\trefs/tags/v1.0.0^{}\n"

5. 总结

最后总结一波:

  1. remote-git-tags使用了child_process.execFile方法来执行命令,并通过promisify将其转换为Promise形式。它接受一个仓库URL作为参数,并返回一个包含tag信息的Map对象。

  2. 通过执行命令并遍历结果,我们将版本和对应的hash值存储在一个Map对象中,并最终获得了版本信息。

如有错误,请指正O^O!

相关推荐
鱼樱前端7 分钟前
别再"学工具"了,先搭你的 AI 工作流
前端·ai编程·前端工程化
凤山老林2 小时前
从美团全栈化看 AI 冲击:前端转全栈,是自救还是必然
前端·人工智能·状态模式
777VG9 小时前
PostgreSQL +martin将多张表输出成一个 MVT
前端·数据库·postgresql
mayaairi10 小时前
JS循环语句深度解析:嵌套for、while与do...while
开发语言·前端·javascript
To_OC10 小时前
啃完流式输出:从一个卡顿的 LLM 接口开始,我搞懂了数据流到底怎么 “流”
前端·javascript·llm
阳光是sunny10 小时前
LangGraph实战教程:defer延迟节点——让收尾工作自动排到最后
前端·人工智能·后端
kyriewen10 小时前
我用了三周Claude Code Skills——总结出5条铁律,第3条最反直觉
前端·ai编程·claude
阳光是sunny10 小时前
LangGraph实战教程:控制流详解
前端·人工智能·后端
格尔曼Noah11 小时前
Safari浏览器中如何只允许指定网站下载
前端·safari
用户0595401744612 小时前
用了3年Redis,才发现我一直没搞懂缓存一致性测试
前端·css