Giter Club home page Giter Club logo

futurize's Introduction

futurize

build status npm version codecov.io

Turn callback-style functions or promises into futures

-function read(path) {
-  return new Future(function(reject, resolve) {
-    fs.readFile(path, function(error, data) {
-      if (error)  reject(error)
-      else        resolve(data)
-    })
-  })
-}

+const read = futurize(Future)(fs.readFile);

Example

Futurize a callback-style function

import { futurize } from 'futurize';
import { Future } from 'ramda-fantasy';
// or
import Task from 'data.task';

const future = futurize(Future); // or futurize(Task);

import { readFile } from 'fs'

const read = future(readFile);

function decode(buffer) {
  return buffer.map(a => a.toString('utf-8'));
}

const readme = decode(read('README.md'));
const license = decode(read('LICENSE.md'));

const concatenated = readme.chain(a => license.map(b => a + b));

concatenated.fork(
  error => console.error(error)
, data => console.log(data)
);

Futurize a callback with multiple arguments

import { futurizeV } from 'futurize';
import { Future } from 'ramda-fantasy';

const futureV = futurizeV(Future);

const read = futureV(fs.read);

read(fs.openSync('package.json', 'r'), new Buffer([]), 0, 2, 0)
.fork(console.error, ([bytesRead, buf]) => {
  console.log(buf.toString('utf8'));
});

Futurize a promise

import { futurizeP } from 'futurize';
import { Future } from 'ramda-fantasy';
// or
import Task from 'data.task';
import myPromisedFunction from 'a-module';

const future = futurizeP(Future); // or futurizeP(Task);

const myFuturizedFunction = future(myPromisedFunction);

API

futurize :: Constructor -> CPS -> ( ...args -> Future )
futurizeP :: Constructor -> Promise -> ( ...args -> Future )

License

MIT © stoeffel

futurize's People

Contributors

avaq avatar greenkeeperio-bot avatar safareli avatar stoeffel avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

futurize's Issues

call a module named "test" in current working path instead of the builtin one

in python2, after futurize,

it add codes:
standard_library.install_aliases()
which have these code inside:
import test

the code is mean to cll python2's standard test module. But if i have a test.py beside my starter.py, when i run starter.py , it will call test.py.

Is it a bug or should i rename all test.py?

Return void from computation

Several libraries, including Fun-Task and Fluture 2.0, use the return value from the computation. This leads to an error in Fluture 2.0:

//npm i futurize fluture@latest request
const req = require('futurize').futurize(require('fluture'))(require('request'));
req('https://github.com').value(console.log);
TypeError: Future#fork expected the computation to return a nullary function or void
  Actual: {"domain": null, "_events": [Object: error, complete, pipe], "_eventsCount": 3, "_maxListeners": undefined, "method": "PUT", "timeout": 2500, "callback": [Function], "readable": true, "writable": true, "explicitMethod": true, "_qs": [Object: request, lib, useQuerystring, parseOptions, stringifyOptions], "_auth": [Object: request, hasAuth, sentAuth, bearerToken, user, pass], "_oauth": [Object: request, params], "_multipart": [Object: request, boundary, chunked, body], "_redirect": [Object: request, followRedirect, followRedirects, followAllRedirects, allowRedirect, maxRedirects, redirects, redirectsFollowed, removeRefererHeader], "_tunnel": [Object: request, proxyHeaderWhiteList, proxyHeaderExclusiveList], "headers": [Object: host], "setHeader": [Function], "hasHeader": [Function], "getHeader": [Function], "removeHeader": [Function], "localAddress": undefined, "pool": [Object: ], "dests": [Array: 0], "__isRequestRequest": true, "_callback": [Function], "uri": [Object: protocol, slashes, auth, host, port, hostname, hash, search, query, pathname, path, href], "proxy": null, "tunnel": false, "setHost": true, "originalCookieHeader": undefined, "_disableCookies": true, "_jar": undefined, "port": "5984", "host": "localhost", "path": "/events/", "httpModule": [Object: IncomingMessage, METHODS, OutgoingMessage, ServerResponse, STATUS_CODES, Agent, globalAgent, ClientRequest, request, get, _connectionListener, Server, createServer, Client, createClient], "agentClass": [Function: Agent], "agent": [Object: domain, _events, _eventsCount, _maxListeners, defaultPort, protocol, options, requests, sockets, freeSockets, keepAliveMsecs, keepAlive, maxSockets, maxFreeSockets]}
  From calling: function (rej, res) /*istanbul ignore next*/{
    return (/*istanbul ignore next*/fn.apply( /*istanbul ignore next*/undefined, args.concat([function (err, result) /*istanbul ignore next*/{
        return err ? rej(err) : res(result);
      }]))
    );
  }
    at check$fork$f
    ...

The problem is the implicitly returned value here. It would be fixed by prefixing void to the statement.

Add a couple ultra simplistic examples to aid understanding

This is not really an issue, but more an attempt to write a helpful suggestion. For users that are new to both Futures and Futurize, I believe a couple of simple examples would help. Fully appreciate you did take the README example for data.task, and having that example is also extremely useful. So I would add these as first examples that build up to what you already have in README.

Would also provide an example that uses common js module syntax - ES6 modules are becoming increasingly popular, but as yet unavailable in NodeJS envs without babel etc.

Example 1 - Hello, futurize!

'use strict';

const Task = require('data.task'),
  futurize = require('futurize').futurize,
  future = futurize(Task);

const helloAsync = (name, cb) => {
  setTimeout(() => {
    return cb(null, `Hello, ${name}`);
  }, 0);
};

const hello = future(helloAsync);

hello('futurize!!!!').fork(
  error => {
    console.error(error);
  }, data => {
    console.log(data);
    //=> Hello, futurize!!!!
  }
);

This next example just does one thing (read/buffer a single file), and is opinionated about using data.task. You are definitely right to show that futurize is not tied to a particular fantasyland Future implementation, but for a very first example it might be better to be specific.

Example 2 - no frills readFile

const fs = require('fs'),
  Task = require('data.task'),
  futurize = require('futurize').futurize,
  future = futurize(Task),
  read = future(fs.readFile);

const decode = (buffer) => {
  return buffer.map(a => a.toString('utf-8'));
};

decode(read('README.md')).fork(
  error => console.error(error)
  , data => console.log(data)
);

Be interested to hear your comments on these.

futurizeP -> response.json() [clarification]

I had situation with resolve fetch promises that should return json

fetch(<apiUrl>)
.then(response => response.json())
.then(json => json)

so i decided to make this

const Task = require("data.task");

const fetchJsonTask = promise =>
  new Task((rej, res) =>
    promise
      .then(response => response.json(),
            error => rej(error))
      .then(res));

module.exports = {
  fetchJsonTask
};

for this code:

const Task = require("data.task");
const Either = require("data.either");
const fetch = require('node-fetch');
const {List, Map} = require('immutable-ext');
const {fetchJsonTask} = require('../utils');

const requiredUserIDs = List([1, 2, 10]);

const getUser = apiUrl => Id =>
  fetchJsonTask(fetch(`${apiUrl}/${Id}`));

const decodeUser = ({id, name, username, email }) => // user
  Map({ id, name, username, email})
    .map(item => Either.fromNullable(item)
    .fold(e => 'Not Specified', r => r));

requiredUserIDs.traverse(Task.of, getUser('https://jsonplaceholder.typicode.com/users'))
  .map(list => list.map(decodeUser))
  .fork(console.error, console.log);

but this avoids to use your library,

Have i done something wrong or could you extend your library ?

Thank you

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.