首页 > 其他 > 详细

[Functional Programming] Use Task/Async for Asynchronous Actions

时间:2019-02-27 16:10:57      阅读:154      评论:0      收藏:0      [点我收藏+]

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 Task = require(data.task);
const fs = require(fs);

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 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!!)
);

 

[Functional Programming] Use Task/Async for Asynchronous Actions

原文:https://www.cnblogs.com/Answer1215/p/10444364.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!