zoukankan      html  css  js  c++  java
  • [Functional Programming] Use Task/Async for Asynchronous Actions

    We refactor a standard node callback style workflow into a composed task-based workflow.

    Original Code:

    const app = () => {
        fs.readFile('config.json', 'utf-8', (err, content) => {
            if (err) throw err;
    
            const newContents = content.replace(/8/g, '6');
    
            fs.writeFile('config1.json', newContents, (err, _) => {
                if (err) throw err;
                console.log('success!');
            })
        });
    }
    
    app();

    Using Task:

    const readFile = (filename) =>
        new Task((rej, res) =>
            fs.readFile(filename, 'utf-8', (err, content) => {
                err ? rej(err) : res(content);
            }));
    const writeFile = (filename, content) =>
        new Task((rej, res) =>
            fs.writeFile(filename, content, (err, success) => {
                err ? rej(err) : res(success);
            }));
    
    const TaskApp = readFile('config.json')
            .map(content => content.replace(/8/g, '6'))
            .chain(newContent => writeFile('config1.json', newContent));
    
    TaskApp.fork(e => console.error(e),
              x => console.log('success!'));

    Using Async:

    const Async = require('crocks/Async');
    const fs = require('fs');
    
    const readF = (filename) =>
      Async((rej, res) =>
        fs.readFile(filename, 'utf-8', (err, content) => {
            err ? rej(err): res(content);
        }));
    
    const writeF = (filename, content) =>
        Async((rej, res) =>
            fs.writeFile(filename, content, (err, success) => {
                err ? rej(err) : res(success)
            }));
    
    const AsyncApp = readF('config.json')
            .map(content => content.replace(/8/g, '6'))
            .chain(newContent => writeF('config2.json', newContent));
    AsyncApp.fork(
        e => console.error(e),
        x => console.log('success!!')
    );
  • 相关阅读:
    前后端项目结构规范性记录
    开发问题记录(这部分还是比较零碎)
    对HashMap的一次记录
    面试问题记录 三 (JavaWeb、JavaEE)
    面试问题记录 二 (数据库、Linux、Redis)
    面试问题记录 一 (基础部分)
    对正则表达式的一些记录
    WEB与游戏开发的一些区别
    MarkDown常用语法全纪录
    MySQL压测相关内容
  • 原文地址:https://www.cnblogs.com/Answer1215/p/10444364.html
Copyright © 2011-2022 走看看