zoukankan      html  css  js  c++  java
  • [Compose] 11. Use Task for Asynchronous Actions

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

    For example we have the code as following:

    We want to wrap async functions (readFile and writeFile) into Task. Therefore it becomes composeable.

    const Task = require('data.task')
    const fs = require('fs')
    
    const readFile = name => 
      new Task((rej, res) => 
              fs.readFile(name, 'utf-8',
                          (err, contents) => err ? rej(err) : res(contents)));
    
    const writeFile = (name, content) => 
      new Task((rej, res) => 
              fs.writeFile(name, contents, 
                           (err, _) => err ? rej(err): res(content)));
    
    const app = () => 
      readFile('config.json') //return Task()
        .map(contents => contents.replace(/8/g, '6'))
        .chain(replaced => wirteFile('config.json',  replaced));  //flat Task(Task()) --> Task()
    
    app.fork(console.error, console.log);
  • 相关阅读:
    DHCP服务搭建
    JumpServer跳板机
    PXE
    DNS
    MySQL
    企业级LNMP分离式部署
    MHA-Atlas-MySQL高可用集群2
    MHA-Atlas-MySQL高可用集群
    备份全网服务器数据
    FTP
  • 原文地址:https://www.cnblogs.com/Answer1215/p/6197973.html
Copyright © 2011-2022 走看看