diff --git a/.gitignore b/.gitignore
index ba423fa..e5e05eb 100644
--- a/.gitignore
+++ b/.gitignore
@@ -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*
diff --git a/.npmignore b/.npmignore
index ca3d002..8f68718 100644
--- a/.npmignore
+++ b/.npmignore
@@ -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
diff --git a/README.md b/README.md
index 2f1b19f..b52e828 100644
--- a/README.md
+++ b/README.md
@@ -1,19 +1,29 @@
DeAsync.js
=======
-[](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 getData. Your users call it to get actual data:
+Suppose you maintain a library that exposes a function getData. Your users call it to get actual data:
var myData = getData();
Under the hood data is saved in a file so you implemented getData using Node.js built-in fs.readFileSync. It's obvious both getData and fs.readFileSync 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, getData 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%.
DeAsync supports both alternatives.
@@ -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
@@ -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
```
@@ -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;
@@ -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
diff --git a/bin/win32-x64-node-10/deasync.node b/bin/win32-x64-node-10/deasync.node
new file mode 100644
index 0000000..29b4817
Binary files /dev/null and b/bin/win32-x64-node-10/deasync.node differ
diff --git a/index.d.ts b/index.d.ts
new file mode 100644
index 0000000..3da0c00
--- /dev/null
+++ b/index.d.ts
@@ -0,0 +1,25 @@
+/**
+ * Created by user on 2018/4/13/013.
+ */
+
+declare namespace DeAsync
+{
+ export interface IApi
+ {
+ (fn: (argv, done: (err: U, value: T) => never) => T, ...argv): T,
+ (fn: (done: (err: U, value: T) => never) => T, ...argv): T,
+ (fn: (...argv) => T, ...argv): T,
+
+ sleep(timeout: number): never,
+ runLoopOnce(): never,
+ loopWhile(pred: (...argv) => boolean): never,
+ await(pr: Promise): T
+
+ default: IApi,
+ }
+}
+
+declare const DeAsync: DeAsync.IApi;
+export = DeAsync;
+
+export as namespace DeAsync;
diff --git a/index.js b/index.js
index 28acb68..6ccb6b0 100644
--- a/index.js
+++ b/index.js
@@ -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];
@@ -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;
@@ -50,22 +50,23 @@
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();
@@ -73,4 +74,26 @@
}
};
+ 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;
+ };
+
}());
diff --git a/package-lock.json b/package-lock.json
deleted file mode 100644
index 6455cec..0000000
--- a/package-lock.json
+++ /dev/null
@@ -1,18 +0,0 @@
-{
- "name": "deasync",
- "version": "0.1.13",
- "lockfileVersion": 1,
- "requires": true,
- "dependencies": {
- "bindings": {
- "version": "1.2.1",
- "resolved": "https://registry.npmjs.org/bindings/-/bindings-1.2.1.tgz",
- "integrity": "sha1-FK1hE4EtLTfXLme0ystLtyZQXxE="
- },
- "nan": {
- "version": "2.10.0",
- "resolved": "https://registry.npmjs.org/nan/-/nan-2.10.0.tgz",
- "integrity": "sha512-bAdJv7fBLhWC+/Bls0Oza+mvTaNQtP+1RyhhhvD95pgUJz6XM5IzgmxOkItJ9tkoCiplvAnXI1tNmmUD/eScyA=="
- }
- }
-}
diff --git a/package.json b/package.json
index 93326db..8b64b43 100644
--- a/package.json
+++ b/package.json
@@ -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 ",
"contributors": [
"Fred Wen (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"
}
diff --git a/test.js b/test.js
index fa4ca1c..23d176b 100644
--- a/test.js
+++ b/test.js
@@ -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);
+}
diff --git a/test/await.demo.js b/test/await.demo.js
new file mode 100644
index 0000000..9d68b34
--- /dev/null
+++ b/test/await.demo.js
@@ -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);
+}