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!!')
    );
  • 相关阅读:
    maven项目报错:Class path contains multiple SLF4J bindings
    ubuntu18.04 点击启动器实现窗口最小化
    Eclipse lombok get set方法报错
    try-with-resources 让java资源关闭代码更简洁
    yang文件语法格式
    RabbitMQ 交换器、持久化
    RabbitMQ 简介
    systemctl命令配置系统服务
    Karaf基础知识
    Linux shell模拟多线程拷贝
  • 原文地址:https://www.cnblogs.com/Answer1215/p/10444364.html
Copyright © 2011-2022 走看看