Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Promises/await support #90

Open
wants to merge 9 commits into
base: master
Choose a base branch
from
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: 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;
43 changes: 32 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,48 @@
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, result;

done = false;
result = undefined;

pr
.then(function(r) {
done = true;
return result = r;
})
.catch(function(err) {
done = true
throw err
})

deasync.loopWhile(() => { return !done });
return result;
Comment on lines +80 to +94
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
done = false;
result = undefined;
pr
.then(function(r) {
done = true;
return result = r;
})
.catch(function(err) {
done = true
throw err
})
deasync.loopWhile(() => { return !done });
return result;
done = false;
result = undefined;
error = undefined;
pr
.then(function(r) {
done = true;
result = r;
})
.catch(function(err) {
done = true;
error = err;
})
deasync.loopWhile(function() { return !done; });
if (error) throw error;
return result;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What about errors what are falsy? for example Promise.reject(0) or Promise.reject(undefined).
This still would no throw an exception

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@NotWearingPants I forgot that those rejections are technically possible. Indeed to cover that it would be better to use a didThrow variable instead.

};

}());
7 changes: 4 additions & 3 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@
"async",
"sync",
"sleep",
"await",
"promise",
"async wrapper"
],
"engines": {
Expand Down
14 changes: 14 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,3 +29,17 @@ 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 ')))
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);
}