美文网首页程序员
TypeScript 代码整洁之道- 并发

TypeScript 代码整洁之道- 并发

作者: 小校有来有去 | 来源:发表于2019-03-02 13:02 被阅读15次

    将 Clean Code 的概念适用到 TypeScript,灵感来自 clean-code-javascript
    原文地址: clean-code-typescript
    中文地址: clean-code-typescript

    简介

    image

    这不是一份 TypeScript 设计规范,而是将 Robert C. Martin 的软件工程著作 《Clean Code》 适用到 TypeScript,指导读者使用 TypeScript 编写易读、可复用和易重构的软件。

    并发

    用 Promises 替代回调

    回调不够整洁而且会导致过多的嵌套(回调地狱)

    有些工具使用回调的方式将现有函数转换为 promise 对象:

    反例:

    
    import { get } from 'request';
    
    import { writeFile } from 'fs';
    
    function downloadPage(url: string, saveTo: string, callback: (error: Error, content?: string) => void){
    
      get(url, (error, response) => {
    
        if (error) {
    
          callback(error);
    
        } else {
    
          writeFile(saveTo, response.body, (error) => {
    
            if (error) {
    
              callback(error);
    
            } else {
    
              callback(null, response.body);
    
            }
    
          });
    
        }
    
      })
    
    }
    
    downloadPage('https://en.wikipedia.org/wiki/Robert_Cecil_Martin', 'article.html', (error, content) => {
    
      if (error) {
    
        console.error(error);
    
      } else {
    
        console.log(content);
    
      }
    
    });
    
    

    正例:

    
    import { get } from 'request';
    
    import { writeFile } from 'fs';
    
    import { promisify } from 'util';
    
    const write = promisify(writeFile);
    
    function downloadPage(url: string, saveTo: string): Promise<string> {
    
      return get(url)
    
        .then(response => write(saveTo, response))
    
    }
    
    downloadPage('https://en.wikipedia.org/wiki/Robert_Cecil_Martin', 'article.html')
    
      .then(content => console.log(content))
    
      .catch(error => console.error(error));  
    
    

    Promise 提供了一些辅助方法,能让代码更简洁:

    方法 描述
    Promise.resolve(value) 返回一个传入值解析后的 promise 。
    Promise.reject(error) 返回一个带有拒绝原因的 promise 。
    Promise.all(promises) 返回一个新的 promise,传入数组中的每个 promise 都执行完成后返回的 promise 才算完成,或第一个 promise 拒绝而拒绝。
    Promise.race(promises) 返回一个新的 promise,传入数组中的某个 promise 解决或拒绝,返回的 promise 就会解决或拒绝。

    Promise.all在并行运行任务时尤其有用,Promise.race让为 Promise 更容易实现超时。

    Async/AwaitPromises 更好

    使用async/await语法,可以编写更简洁、更易理解的链式 promise 的代码。一个函数使用async关键字作为前缀,JavaScript 运行时会暂停await关键字上的代码执行(当使用 promise 时)。

    反例:

    
    import { get } from 'request';
    
    import { writeFile } from 'fs';
    
    import { promisify } from 'util';
    
    const write = util.promisify(writeFile);
    
    function downloadPage(url: string, saveTo: string): Promise<string> {
    
      return get(url).then(response => write(saveTo, response))
    
    }
    
    downloadPage('https://en.wikipedia.org/wiki/Robert_Cecil_Martin', 'article.html')
    
      .then(content => console.log(content))
    
      .catch(error => console.error(error));  
    
    

    正例:

    
    import { get } from 'request';
    
    import { writeFile } from 'fs';
    
    import { promisify } from 'util';
    
    const write = promisify(writeFile);
    
    async function downloadPage(url: string, saveTo: string): Promise<string> {
    
      const response = await get(url);
    
      await write(saveTo, response);
    
      return response;
    
    }
    
    // somewhere in an async function
    
    try {
    
      const content = await downloadPage('https://en.wikipedia.org/wiki/Robert_Cecil_Martin', 'article.html');
    
      console.log(content);
    
    } catch (error) {
    
      console.error(error);
    
    }
    
    

    上一章:TypeScript 代码整洁之道 - 测试
    下一章:TypeScript 代码整洁之道- 错误处理

    相关文章

      网友评论

        本文标题:TypeScript 代码整洁之道- 并发

        本文链接:https://www.haomeiwen.com/subject/btyeuqtx.html