Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 24 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,9 +1,32 @@
/build
/node_modules
/.project
/bin
/.c9
/.node-gyp
/test/
/node-src/
*.sublime-workspace
### git2 template
.idea

~ci.list.txt
~ci.log.txt
~ci.errors.txt

*.stackdump
*.bak
*.old

package-lock.json

test/**/*.js
test/**/*.d.ts
test/*.js
test/*.d.ts
test/temp*

tests/**/*.js
tests/**/*.d.ts
tests/*.js
tests/*.d.ts
tests/temp*
22 changes: 22 additions & 0 deletions .npmignore
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,25 @@ test/
node-src/
*.sublime-project
*.sublime-workspace

### npm template
.idea

~ci.list.txt
~ci.log.txt
~ci.errors.txt

*.stackdump
*.bak
*.old

tsconfig.json
#package-lock.json

test

.github
.gitkeep

/.*
!/build.js
27 changes: 19 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,19 +1,29 @@
DeAsync.js
=======
[![NPM version](http://img.shields.io/npm/v/deasync.svg)](https://www.npmjs.org/package/deasync)

DeAsync turns async function into sync, implemented with a blocking mechanism by calling Node.js event loop at JavaScript layer. The core of deasync is writen in C++.

*this is a fork of fork* add support promise

* [bluelovers/deasync](https://github.com/bluelovers/deasync)
* [malyutinegor/deasync](https://github.com/malyutinegor/deasync)
* [abbr/deasync](https://github.com/abbr/deasync)

## install

```nodemon
npm install deasync2
```

## Motivation

Suppose you maintain a library that exposes a function <code>getData</code>. Your users call it to get actual data:
Suppose you maintain a library that exposes a function <code>getData</code>. Your users call it to get actual data:
<code>var myData = getData();</code>
Under the hood data is saved in a file so you implemented <code>getData</code> using Node.js built-in <code>fs.readFileSync</code>. It's obvious both <code>getData</code> and <code>fs.readFileSync</code> are sync functions. One day you were told to switch the underlying data source to a repo such as MongoDB which can only be accessed asynchronously. You were also told to avoid pissing off your users, <code>getData</code> API cannot be changed to return merely a promise or demand a callback parameter. How do you meet both requirements?

You may tempted to use [node-fibers](https://github.com/laverdet/node-fibers) or a module derived from it, but node fibers can only wrap async function call into a sync function inside a fiber. In the case above you cannot assume all callers are inside fibers. On the other hand, if you start a fiber in `getData` then `getData` itself will still return immediately without waiting for the async call result. For similar reason ES6 generators introduced in Node v0.11 won't work either.
You may tempted to use [node-fibers](https://github.com/laverdet/node-fibers) or a module derived from it, but node fibers can only wrap async function call into a sync function inside a fiber. In the case above you cannot assume all callers are inside fibers. On the other hand, if you start a fiber in `getData` then `getData` itself will still return immediately without waiting for the async call result. For similar reason ES6 generators introduced in Node v0.11 won't work either.

What really needed is a way to block subsequent JavaScript from running without blocking entire thread by yielding to allow other events in the event loop to be handled. Ideally the blockage is removed as soon as the result of async function is available. A less ideal but often acceptable alternative is a `sleep` function which you can use to implement the blockage like ```while(!done) sleep(100);```. It is less ideal because sleep duration has to be guessed. It is important the `sleep` function not only shouldn't block entire thread, but also shouldn't incur busy wait that pegs the CPU to 100%.
What really needed is a way to block subsequent JavaScript from running without blocking entire thread by yielding to allow other events in the event loop to be handled. Ideally the blockage is removed as soon as the result of async function is available. A less ideal but often acceptable alternative is a `sleep` function which you can use to implement the blockage like ```while(!done) sleep(100);```. It is less ideal because sleep duration has to be guessed. It is important the `sleep` function not only shouldn't block entire thread, but also shouldn't incur busy wait that pegs the CPU to 100%.
</small>

DeAsync supports both alternatives.
Expand All @@ -22,11 +32,12 @@ DeAsync supports both alternatives.

## Usages

* [await.demo.js](test/await.demo.js)

* Generic wrapper of async function with standard API signature `function(p1,...pn,function cb(error,result){})`. Returns `result` and throws `error` as exception if not null:

```javascript
var deasync = require('deasync');
var deasync = require('deasync2');
var cp = require('child_process');
var exec = deasync(cp.exec);
// output result of ls -la
Expand All @@ -49,7 +60,7 @@ asyncFunction(p1,function cb(res){
data = res;
done = true;
});
require('deasync').loopWhile(function(){return !done;});
require('deasync2').loopWhile(function(){return !done;});
// data is now populated
```

Expand All @@ -62,7 +73,7 @@ function SyncFunction(){
ret = "hello";
},3000);
while(ret === undefined) {
require('deasync').sleep(100);
require('deasync2').sleep(100);
}
// returns hello with sleep; undefined without
return ret;
Expand All @@ -74,7 +85,7 @@ Except on a few [ platforms + Node version combinations](https://github.com/abbr

To install, run

```npm install deasync```
```npm install deasync2```


## Recommendation
Expand Down
Binary file added bin/win32-x64-node-10/deasync.node
Binary file not shown.
25 changes: 25 additions & 0 deletions index.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/**
* Created by user on 2018/4/13/013.
*/

declare namespace DeAsync
{
export interface IApi
{
<T>(fn: (argv, done: <U extends Error>(err: U, value: T) => never) => T, ...argv): T,
<T>(fn: (done: <U extends Error>(err: U, value: T) => never) => T, ...argv): T,
<T>(fn: (...argv) => T, ...argv): T,

sleep(timeout: number): never,
runLoopOnce(): never,
loopWhile(pred: (...argv) => boolean): never,
await<T>(pr: Promise<T>): T

default: IApi,
}
}

declare const DeAsync: DeAsync.IApi;
export = DeAsync;

export as namespace DeAsync;
45 changes: 34 additions & 11 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,17 @@
* Copyright 2014-2015 Abbr
* Released under the MIT license
*/

(function () {

var fs = require('fs'),
path = require('path'),
binding;

// Seed random numbers [gh-82] if on Windows. See https://github.com/laverdet/node-fibers/issues/82
if(process.platform === 'win32') Math.random();


// Look for binary for this platform
var nodeV = 'node-' + /[0-9]+\.[0-9]+/.exec(process.versions.node)[0];
var nodeVM = 'node-' + /[0-9]+/.exec(process.versions.node)[0];
Expand All @@ -41,7 +41,7 @@
var res;

fn.apply(this, args);
module.exports.loopWhile(function(){return !done;});
module.exports.loopWhile(function(){ return !done; });
if (err)
throw err;

Expand All @@ -50,27 +50,50 @@
function cb(e, r) {
err = e;
res = r;
done = true;
done = true;
}
}
}

module.exports = deasync;

module.exports.default = deasync;

module.exports.sleep = deasync(function(timeout, done) {
setTimeout(done, timeout);
});

module.exports.runLoopOnce = function(){
process._tickCallback();
binding.run();
};

module.exports.loopWhile = function(pred){
while(pred()){
process._tickCallback();
if(pred()) binding.run();
}
};

module.exports.await = function(pr) {
var done = false;
var rejected = false;
var resolutionResult = undefined;
var rejectionResult = undefined;

pr.then(function(r) {
done = true;
resolutionResult = r;
}).catch(function(e) {
done = true;
rejected = true;
rejectionResult = e;
});
deasync.loopWhile(() => { return !done });

if (rejected) {
throw rejectionResult;
}
return resolutionResult;
};

}());
18 changes: 0 additions & 18 deletions package-lock.json

This file was deleted.

51 changes: 34 additions & 17 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,31 +1,48 @@
{
"name": "deasync",
"version": "0.1.13",
"name": "deasync2",
"version": "1.0.1",
"description": "Turns async function into sync via JavaScript wrapper of Node event loop",
"main": "index.js",
"keywords": [
"async",
"async wrapper",
"await",
"coroutine",
"fiber",
"fibers",
"future",
"parallel",
"promise",
"sleep",
"sync",
"thread",
"worker"
],
"homepage": "https://github.com/bluelovers/deasync#readme",
"bugs": {
"url": "https://github.com/bluelovers/deasync/issues"
},
"repository": {
"type": "git",
"url": "git+https://github.com/bluelovers/deasync.git"
},
"license": "MIT",
"author": "Vladimir Kurchatkin <[email protected]>",
"contributors": [
"Fred Wen <[email protected]> (https://github.com/abbr)"
],
"license": "MIT",
"types": "index.d.ts",
"main": "index.js",
"directories": {
"test": "test"
},
"scripts": {
"install": "node ./build.js"
},
"dependencies": {
"bindings": "~1.2.1",
"nan": "^2.0.7"
},
"repository": {
"type": "git",
"url": "https://github.com/abbr/deasync.git"
"bindings": "~1.3.0",
"nan": "^2.10.0"
},
"homepage": "https://github.com/abbr/deasync",
"keywords": [
"async",
"sync",
"sleep",
"async wrapper"
],
"devDependencies": {},
"engines": {
"node": ">=0.11.0"
}
Expand Down
20 changes: 20 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,3 +29,23 @@ setTimeout(function () {
console.log(exec('ls -la'));
sleep(2000);
console.log(request('http://nodejs.org'));

function sleepAsync(time) {
return new Promise(function(resolve, reject) {
setTimeout(function() {
resolve()
}, time)
})
}
async function trim(str) {
await sleepAsync(2000)
return str.trim()
}

console.log(deasync.await(trim(' hello ')))

try {
deasync.await(Promise.reject("Should result in exception"));
} catch(e) {
console.log("Got expected exception:", e);
}
32 changes: 32 additions & 0 deletions test/await.demo.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/**
* Created by user on 2018/4/13/013.
*/

const deasync = require("..");
const timstamp = Date.now();

function f(n)
{
return new Promise(function (done)
{
setTimeout(done, n);
})
.then(function ()
{
logWithTime(n);
});
}

console.time();
f(500);
let p = f(1500);
deasync.sleep(1000);
//msleep(1000);
logWithTime(1000);
deasync.await(p);
console.timeEnd();

function logWithTime(...argv)
{
console.log(`[${Date.now() - timstamp}]`, ...argv);
}