yortus / asyncawait Goto Github PK
View Code? Open in Web Editor NEWCallback heaven for Node.js with async/await
License: MIT License
Callback heaven for Node.js with async/await
License: MIT License
sync version is faster than async
var SELECTED_FUNCTION = functions.countFiles;
var SELECTED_VARIANT = variants.synchronous;
var SAMPLES_PER_RUN = 10000;
10393.929944912172 samples/sec
vs
var SELECTED_VARIANT = variants.callbacks;
6764.069264069263 samples/sec
If we are not in node-like environment and we would like to have the asyncawait library running just in the browser, how can we do it?
For example, to the code below, how can we put it to work?
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript' src='asyncawait.bundle.js'></script>
<script type='text/javascript'>
async function slow() {
return new Promise(function(resolve, reject) {
setTimeout(function() {
console.log("slow finished");
resolve();
}, 3000);
});
}
function fast() {
console.log("fast");
}
async function run() {
await slow();
fast();
}
run();
</script>
</head>
<body>
</body>
</html>
I'm trying to use these method in my project but it's give me error when call await
. Please check follow details.
code structure is :
var await = require('asyncawait/await');
fiber(function() {
Promise
.then(() => {
var settingParameter = await (require('./settingObjects_2.js')(req));
})
});
settingObjects_2.js
module.exports = function(){
}
ERROR :
An unrelayed rejection happens:
Error: await functions, yield functions, and value-returning suspendable functions may only be called from inside a suspendable function.
at await (/home/snow22/workspace/svn_checkout/MIXTTS/jira/TTS-103/node_modules/asyncawait/src/await/makeAwaitFunc.js:20:19)
Github will not let me leave more comments in the original issue:
#48
... so I'm creating a new issue here. The error is "You can't perform that action at this time" when I try to leave a comment. Here is the comment:
To use this asyncawait library with ES6 classes, why not just add the async function to the class prototype? That seems easy and direct:
const async = require('asyncawait/async')
const await = require('asyncawait/await')
class MyClass {
firstMethod() {
console.log('firstMethod')
}
}
MyClass.prototype.secondMethod = async(function () {console.log(await('secondMethod'))})
const myClassInstance = new MyClass()
console.log(myClassInstance.firstMethod())
myClassInstance.secondMethod().then(function (data) { console.log(data)})```
Output is:
firstMethod
secondMethod
Please let me know if I am missing something here.
Can anyone give a reason getting the message below. Fibers built from npm install only produces
win32-x64-v8-5.0, not win32-x64-v8-5.1?
I'm running electron v1.2.0; node v6.2.0; npm v3.8.9; chromedriver 2.21
C:\Users\Thomas\electron\eqs\node_modules\fibers\fibers.js:16 Uncaught Error: C:\Users\Thomas\electron\eqs\node_modules\fibers\bin\win32-x64-v8-5.1\fibers.node
is missing. Try reinstalling node-fibers
?
I tried using bluebird's .nodeify
, here's an example below.
function execModify(command, manipulators, callback) {
return async(function(command, manipulators) {
var exec = Promise.promisify(childProcess.exec);
var stdout = await(exec(command))[0];
if (!manipulators) return stdout;
return _.map(manipulators, function(manipulator) {
return manipulator(stdout);
});
}).nodeify(callback);
}
Hi,
While I can get your examples to work without an issue, I'm not able to run the following sample code
var async = require('asyncawait/async');
var await = require('asyncawait/await');
var Promise = require("bluebird");
var anArray = [];
var testObj = {
'a': '1',
'b': '2',
'c': '3'
};
// this is line 68
async.forEachOf(testObj, function (elem, key, callback) {
console.log(elem);
anArray.push(elem);
return callback(); //<-- the fix. D'oh.
}, function (err) {
if (err) {
console.error(err.message);
}
console.log("This line should be printed at the end.", anArray);
})
error
error: Server Error (500)
error: TypeError: undefined is not a function
at module.exports.claimdocsjoined (C:\Sails10\MEANS-Scibal\api\controllers\ClaimdocsController.js:69:7)
It seems exceptions get logged and then swallowed by the async fn. So i can't apply the pattern of letting the server crash, because it swallows the exception. So neither 'uncaughtException'
or 'unhandledRejection'
get even fired.
So doing something like this
async(function() {
new Promise(function(resolve, reject) {
setTimeout((function() {
reject(new Error("Lets die"));
}), 15);
});
})();
Or even this
async(function() {
throw new Error("Die!!");
})();
Will log the error, but that's it, the server will keep running, and there is no way to catch the 'unhandledRejection'
event since it never fires.
error log example:
Possibly unhandled Error: Die!!
at C:\myapp\api\controllers\traits\restfulTraits.coffee:42:19
at tryBlock (C:\myapp\node_modules\asyncawait\src\async\fiberManager.js:39:33)
at runInFiber (C:\myapp\node_modules\asyncawait\src\async\fiberManager.js:26:9)
.... more stacktrace
Is this the expected behavior, or is it a bug? When i use try catch everything works as expected, but i only use those to catch exceptions i know might happen, not to catch bugs, i want my server to crash when an error is not caught by anything and get at least one of process 'uncaughtException'
or 'unhandledRejection'
events to be fired.
I hope i made myself clear, if not let me know and i'll try to explain better, and if i'm doing something wrong, let me know that too. I'm getting this behavior inside sails.js controller methods (actions), so i must admit i haven't isolated the issue, but i can assume my examples are valid.
Thanks in advance
pst: I love this module :)
Hi. I'm about to loose whats left of my sanity, please help.
What I'm trying do achieve is a 1,2,3 on console, but tryied until my brain dissolve and nothing.
var Seriate = require("seriate");
var async = require("asyncawait/async");
var await = require("asyncawait/await");
function Test(){
var sql = 'select * from my_sqlserver_table';
console.log('1 - Start');
var doQuery = async (
function (sql) {
Seriate.setDefaultConfig(config_obj_set_elsewhere);
var r = await ( Seriate.execute({
query: sql
}));
console.log('2 - Results: ' + r);
return r;
}
);
doQuery(sql);
console.log('3 - End');
}
Any help would be much apreciated.
Thanx in advance
I just tried out your library since it looks a bit nicer than co. I am trying to get this to work with Mongoose/Keystone (which just uses mongoose).
Trying the following code:
var foo = async (function() {
var q = await (keystone.list('Post').find().exec());
return q;
});
EDIT: The exception was my mistake, since I forgot another async
library is already loeaded.
Importing it now as asyncs
and if I try to console.log(foo)
it just prints [Function: f0]
and the complete app seems to stall, as in the site loads forever.
Any idea what the cause could be? Something I am doing wrong? Or incompatibility of Mongoose?
Edit2: Playing around with it a bit more and adding a console.log within the async function doesn't print anything, not even before the await line.
thomas@workstation:new$ npm i asyncawait --save
npm info it worked if it ends with ok
npm info using [email protected]
npm info using [email protected]
npm WARN package.json [email protected] No description
npm WARN package.json [email protected] No repository field.
npm WARN package.json [email protected] No README data
npm info attempt registry request try #1 at 14:26:19
npm http request GET http://registry.npmjs.org/asyncawait
npm http 304 http://registry.npmjs.org/asyncawait
npm info install [email protected] into /Users/thomas/Desktop/recents/wallpaper/new
npm info installOne [email protected]
npm info preinstall [email protected]
npm info attempt registry request try #1 at 14:26:20
npm http request GET http://registry.npmjs.org/bluebird
npm info attempt registry request try #1 at 14:26:20
npm http request GET http://registry.npmjs.org/fibers
npm info attempt registry request try #1 at 14:26:20
npm http request GET http://registry.npmjs.org/lodash
npm http 304 http://registry.npmjs.org/fibers
npm http 200 http://registry.npmjs.org/bluebird
npm http 200 http://registry.npmjs.org/lodash
npm info retry fetch attempt 1 at 14:26:21
npm info attempt registry request try #1 at 14:26:21
npm http fetch GET http://registry.npmjs.org/lodash/-/lodash-2.4.1.tgz
npm http fetch 200 http://registry.npmjs.org/lodash/-/lodash-2.4.1.tgz
npm info install [email protected] into /Users/thomas/Desktop/recents/wallpaper/new/node_modules/asyncawait
npm info install [email protected] into /Users/thomas/Desktop/recents/wallpaper/new/node_modules/asyncawait
npm info install [email protected] into /Users/thomas/Desktop/recents/wallpaper/new/node_modules/asyncawait
npm info installOne [email protected]
npm info installOne [email protected]
npm info installOne [email protected]
npm info preinstall [email protected]
npm info build /Users/thomas/Desktop/recents/wallpaper/new/node_modules/asyncawait/node_modules/fibers
npm info linkStuff [email protected]
npm info install [email protected]
> [email protected] install /Users/thomas/Desktop/recents/wallpaper/new/node_modules/asyncawait/node_modules/fibers
> node ./build.js
child_process: customFds option is deprecated, use stdio instead.
gyp info it worked if it ends with ok
gyp info using [email protected]
gyp info using [email protected] | darwin | x64
child_process: customFds option is deprecated, use stdio instead.
gyp info spawn python
gyp info spawn args [ '/Users/thomas/.nvm/versions/io.js/v1.6.2/lib/node_modules/npm/node_modules/node-gyp/gyp/gyp_main.py',
gyp info spawn args 'binding.gyp',
gyp info spawn args '-f',
gyp info spawn args 'make',
gyp info spawn args '-I',
gyp info spawn args '/Users/thomas/Desktop/recents/wallpaper/new/node_modules/asyncawait/node_modules/fibers/build/config.gypi',
gyp info spawn args '-I',
gyp info spawn args '/Users/thomas/.nvm/versions/io.js/v1.6.2/lib/node_modules/npm/node_modules/node-gyp/addon.gypi',
gyp info spawn args '-I',
gyp info spawn args '/Users/thomas/.node-gyp/1.6.2/common.gypi',
gyp info spawn args '-Dlibrary=shared_library',
gyp info spawn args '-Dvisibility=default',
gyp info spawn args '-Dnode_root_dir=/Users/thomas/.node-gyp/1.6.2',
gyp info spawn args '-Dmodule_root_dir=/Users/thomas/Desktop/recents/wallpaper/new/node_modules/asyncawait/node_modules/fibers',
gyp info spawn args '--depth=.',
gyp info spawn args '--no-parallel',
gyp info spawn args '--generator-output',
gyp info spawn args 'build',
gyp info spawn args '-Goutput_dir=.' ]
gyp info spawn make
gyp info spawn args [ 'BUILDTYPE=Release', '-C', 'build' ]
CXX(target) Release/obj.target/fibers/src/fibers.o
../src/fibers.cc:140:3: error: no member named 'SetResourceConstraints' in namespace 'v8'; did you mean simply 'SetResourceConstraints'?
v8::SetResourceConstraints(isolate, constraints);
^~~~~~~~~~~~~~~~~~~~~~~~~~
SetResourceConstraints
../src/fibers.cc:139:7: note: 'SetResourceConstraints' declared here
void SetResourceConstraints(Isolate* isolate, ResourceConstraints* constraints) {
^
1 error generated.
make: *** [Release/obj.target/fibers/src/fibers.o] Error 1
gyp ERR! build error
gyp ERR! stack Error: `make` failed with exit code: 2
gyp ERR! stack at ChildProcess.onExit (/Users/thomas/.nvm/versions/io.js/v1.6.2/lib/node_modules/npm/node_modules/node-gyp/lib/build.js:267:23)
gyp ERR! stack at emitTwo (events.js:87:13)
gyp ERR! stack at ChildProcess.emit (events.js:169:7)
gyp ERR! stack at Process.ChildProcess._handle.onexit (child_process.js:1044:12)
gyp ERR! System Darwin 14.1.0
gyp ERR! command "/Users/thomas/.nvm/versions/io.js/v1.6.2/bin/iojs" "/Users/thomas/.nvm/versions/io.js/v1.6.2/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild" "--release"
gyp ERR! cwd /Users/thomas/Desktop/recents/wallpaper/new/node_modules/asyncawait/node_modules/fibers
gyp ERR! node -v v1.6.2
gyp ERR! node-gyp -v v1.0.2
gyp ERR! not ok
Build failed
npm info preinstall [email protected]
npm info build /Users/thomas/Desktop/recents/wallpaper/new/node_modules/asyncawait/node_modules/lodash
npm info linkStuff [email protected]
npm info install [email protected]
npm info postinstall [email protected]
npm info preinstall [email protected]
npm info build /Users/thomas/Desktop/recents/wallpaper/new/node_modules/asyncawait/node_modules/bluebird
npm info linkStuff [email protected]
npm info install [email protected]
npm info postinstall [email protected]
npm info [email protected] Failed to exec install script
npm ERR! Darwin 14.1.0
npm ERR! argv "/Users/thomas/.nvm/versions/io.js/v1.6.2/bin/iojs" "/Users/thomas/.nvm/versions/io.js/v1.6.2/bin/npm" "i" "asyncawait" "--save"
npm ERR! node v1.6.2
npm ERR! npm v2.7.1
npm ERR! code ELIFECYCLE
npm ERR! [email protected] install: `node ./build.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] install script 'node ./build.js'.
npm ERR! This is most likely a problem with the fibers package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR! node ./build.js
npm ERR! You can get their info via:
npm ERR! npm owner ls fibers
npm ERR! There is likely additional logging output above.
npm info preuninstall [email protected]
npm info uninstall [email protected]
npm info postuninstall [email protected]
npm info preuninstall [email protected]
npm info uninstall [email protected]
npm info postuninstall [email protected]
npm ERR! Please include the following file with any support request:
npm ERR! /Users/thomas/Desktop/recents/wallpaper/new/npm-debug.log
Sorry for the basic question, how could asyncawait be used for the native setTimeout
in Node?
I presume it would still have to use thunkify? If so, how might that be done?
From the examples I can see delay examples with bluebird, but I want to explore alternatives - partly for learning, and partly to avoid larger libraries that I don't understand (yet).
Really appreciated
I am a bit lost here. My project is fully written in TS with WebAPI backend, so I have never touched NodeJS.
I did manage to get npm to work and did npm install asyncawait and I got a bunch of files.
But what am I supposed to do next? I see that await.js is almost empty, how can I build the source to a release point?
Or is this project nodeJS only?
I have a library written using the async/await pattern. I try to consume it from a library which uses callbacks. Here is a sample code:
var async = require('asyncawait/async');
var await = require('asyncawait/await');
var Promise = require('bluebird');
var foo = async (function() {
var resultA = await (Promise.promisify(bar));
return 111;
})
function bar(callback) {
setTimeout(callback, 2000)
}
function moo() {
var f = async.cps(foo)
f(function(err, res) {
console.log(res)
})
}
moo()
I expected console.log to print 111 but instead it prints:
{ _bitField: 0,
_fulfillmentHandler0: undefined,
_rejectionHandler0: undefined,
_progressHandler0: undefined,
_promise0: undefined,
_receiver0: undefined,
_settledValue: undefined }
btw if I inline foo in the async.cps line it works (but this is not an option since its an external library).
Any idea?
Hey guys.
I want to know if there's any best practices in how to deal with a array of promises, like:
var arr = await([promise1, promise2, promise3, ...])
Suppose some of the these promises gets rejected. How do I catch the errors?
I see a simple try/catch block won't work, because this would interrupt the async flow of the promises executing and also it would be impossible to determine which promise raised the exception.
Is there any recommended ways to deal with this situation?
This is more a question than an actual bug I suppose, but I just wanted to post this plugin to awesome-nodejs but sindresorhus said that node-fibres is too fragile and he would only include it in the list if it would depend on generators as seen here: sindresorhus/awesome-nodejs#96
Any idea what that remark could refer to? What is your opinion on this @yortus?
Error occurs when trying to use await/async functions.
Here is full stacktrace returned by node
test.js
'use strict';
var async = require('asyncawait/async');
var await = require('asyncawait/await');
var Promise = require('bluebird');
var fs = require("fs");
function existsAsync(path) {
return new Promise(function (resolve) {
fs.exists(path, resolve);
});
}
var doneAsync = async (function(file1, file2){
var afound = await ( existsAsync(file1) );
if (!afound) {
console.log('doneAsync vm notfound : %s', file1);
return false;
}
var bfound= await ( existsAsync(file2) );
if (!bfound) {
console.log('doneAsync notfound : %s', file2);
return false;
}
return true;
});
doneAsync('package.json', 'test.js').then(function(existsAll) {
console.log(existsAll)
})
console like below
D:\>set NODE_ENV=development
D:\>node test.js
Warning: a promise was created in a handler but was not returned from it
at processImmediate [as _immediateCallback] (timers.js:383:17)
From previous event:
at existsAsync (D:\test.js:10:12)
at D:\test.js:21:24
From previous event:
at await (D:\node_modules\asyncawait\src\await\makeAwaitFunc.js:37:18)
at D:\test.js:16:18
at tryBlock (D:\node_modules\asyncawait\src\async\fiberManager.js:39:33)
at runInFiber (D:\node_modules\asyncawait\src\async\fiberManager.js:26:9)
true
I think fixed like this
https://github.com/yortus/asyncawait/blob/master/src/await/makeAwaitFunc.ts#L48
var fiber = Fiber.current;
if (expr && _.isFunction(expr.then)) {
// A promise: resume the coroutine with the resolved value, or throw the rejection value into it.
//expr.then(val => { fiber.run(val); fiber = null; }, err => { fiber.throwInto(err); fiber = null; });
//fixed > not warning
expr.then(val => { fiber.run(val); fiber = null; return val; }, err => { fiber.throwInto(err); fiber = null; });
}
I'm in love with this library if it works! I tried the following code which is supposed to work according to documentation but I get the following error.
var a is a promise and it works just fine and it prints but awaiting it would throw an error.
var async = require('asyncawait/async');
var await = require('asyncawait/await');
var Promise = require('bluebird');
var fs = Promise.promisifyAll(require('fs'));
var a = fs.readFileAsync('data.txt', 'utf8');
a.then(function(v){console.log(v)});
var b = await(fs.readFileAsync('data.txt', 'utf8'));
throw new Error('await functions, yield functions, and value-retur
^
Error: await functions, yield functions, and value-returning suspendable functions may only be called from inside a suspendable function.
Can I use it in angular? How can I do it?
Thank you
When async await feature lands in V8, won't it break your library as async and await will become keyword in javascript.
I found out that if my function has exactly 9 parameters, the value of the 9th one is always replaced with the value 8.
Test case:
var async, await, test;
async = require('asyncawait/async');
await = require('asyncawait/await');
test = async(function(a, b, c, d, e, f, g, h, i) {
console.log("a: " + a);
console.log("b: " + b);
console.log("c: " + c);
console.log("d: " + d);
console.log("e: " + e);
console.log("f: " + f);
console.log("g: " + g);
console.log("h: " + h);
console.log("i: " + i);
});
await(test('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'));
Output is:
a: a
b: b
c: c
d: d
e: e
f: f
g: g
h: h
i: 8
If I add one/remove one parameter from the function, everything is fine. If I remove the async
part of the test
method, everything is fine: the parameter value is unchanged.
What is going on here! :-)
Node version v4.1.2, asyncawait version 1.0.3.
I checked on v0.12.7, it works.
Super awesome project.
How can I install this npm module into node version v0.10.33?
Is there any way..?
env:
node: 0.11.14
os: osx10.10
Failed at the [email protected] install script.
It seems that [email protected] update the v8, so v8's apis changed?
In the documentation (https://github.com/yortus/asyncawait) it says that "will include a useable stack trace". But it does not for me. So I think I am doing it wrong..but I don't know what I'm doing wrong.
To demonstrate I will compare the stacktrace of a "vanilla" bluebird example with the corresponding stacktrace of the correspoding asyncawait code (asyncawait uses bluebird internally so I think it's fair).
First my bluebird code without asyncawait:
var funcB = (function() {
return Promise.resolve().then(function() {
throw new Error("some err");
})
});
var funcA = function() {
return funcB();
};
gulp.task("aa",function(cb) {
funcA().then(function() {
cb();
});
});
The stacktrace yields the information "funcA -> funcB -> exception" at first glace. Perfect!
Error: Error: some err
at processImmediate [as _immediateCallback] (timers.js:358:17)
From previous event:
at funcB (C:\projects\JSBuildHelper\JSBuildHelper\tmp\tsreq\app\gulpfile.js:156:30)
at funcA (C:\projects\JSBuildHelper\JSBuildHelper\tmp\tsreq\app\gulpfile.js:161:12)
at Gulp.<anonymous> (C:\projects\JSBuildHelper\JSBuildHelper\tmp\tsreq\app\gulpfile.js:164:5)
at module.exports (C:\projects\JSBuildHelper\JSBuildHelper\node_modules\gulp\node_modules\orchestrator\lib\runTask.js:34:7)
at Gulp.Orchestrator._runTask (C:\projects\JSBuildHelper\JSBuildHelper\node_modules\gulp\node_modules\orchestrator\index.js:273:3)
at Gulp.Orchestrator._runStep (C:\projects\JSBuildHelper\JSBuildHelper\node_modules\gulp\node_modules\orchestrator\index.js:214:10)
at Gulp.Orchestrator.start (C:\projects\JSBuildHelper\JSBuildHelper\node_modules\gulp\node_modules\orchestrator\index.js:134:8)
at C:\Users\alex\AppData\Roaming\npm\node_modules\gulp\bin\gulp.js:129:20
at process._tickCallback (node.js:355:11)
at Function.Module.runMain (module.js:503:11)
at startup (node.js:129:16)
at node.js:814:3
Now my asyncawait code:
var funcB = async(function() {
throw new Error("some err");
});
var funcA = async(function () {
await(funcB());
});
gulp.task("aa", function(cb) {
funcA().then(function() {
cb();
});
});
In the corresponding stacktrace I only see the exception. No "funcA", no "funcB".
For this simple program it is sufficient. But I can't use it for other more complex stuff, considering how important stacktrances really are..
Possibly unhandled Error: Error: some err
at catchBlock (C:\projects\JSBuildHelper\JSBuildHelper\node_modules\asyncawait\src\async\fiberManager.js:51:25)
at runInFiber (C:\projects\JSBuildHelper\JSBuildHelper\node_modules\asyncawait\src\async\fiberManager.js:29:9)
From previous event:
at new Promise (C:\projects\JSBuildHelper\JSBuildHelper\node_modules\asyncawait\node_modules\bluebird\js\main\promise.js:84:37)
at defer (C:\projects\JSBuildHelper\JSBuildHelper\node_modules\asyncawait\src\async\defer.js:6:19)
at nonIterable (C:\projects\JSBuildHelper\JSBuildHelper\node_modules\asyncawait\src\async\makeAsyncFunc.js:86:28)
at f0 (C:\projects\JSBuildHelper\JSBuildHelper\node_modules\asyncawait\src\async\makeAsyncFunc.js:119:23)
at Gulp.<anonymous> (C:\projects\JSBuildHelper\JSBuildHelper\tmp\tsreq\app\gulpfile.js:162:5)
at module.exports (C:\projects\JSBuildHelper\JSBuildHelper\node_modules\gulp\node_modules\orchestrator\lib\runTask.js:34:7)
at Gulp.Orchestrator._runTask (C:\projects\JSBuildHelper\JSBuildHelper\node_modules\gulp\node_modules\orchestrator\index.js:273:3)
at Gulp.Orchestrator._runStep (C:\projects\JSBuildHelper\JSBuildHelper\node_modules\gulp\node_modules\orchestrator\index.js:214:10)
at Gulp.Orchestrator.start (C:\projects\JSBuildHelper\JSBuildHelper\node_modules\gulp\node_modules\orchestrator\index.js:134:8)
at C:\Users\alex\AppData\Roaming\npm\node_modules\gulp\bin\gulp.js:129:20
at Function.Module.runMain (module.js:503:11)
at startup (node.js:129:16)
at node.js:814:3
Am I doing it wrong or is this really a limitition that I cannot remove?
code:
var fs = require('fs');
var Promise = require('bluebird');
var async = require('asyncawait/async');
var await = require('asyncawait/await');
// A function that returns a promise.
function delay(milliseconds) {
return Promise.delay(milliseconds);
}
var parallelThreadFunc = function() {
console.log("1");
await(delay(1010));
console.log("2");
throw new Error("sfdfsfds");
};
var parallelThreadAsync = async(parallelThreadFunc);
// Another synchronous-looking function written in async/await style.
var program = async.thunk (function () {
try {
console.log('zero...');
// this line was edited after submitting the issue,
// it was starting with "async", however bug is reproduced with await of course
await(parallelThreadAsync(), parallelThreadAsync());
} catch (ex) {
console.log('Caught an error', ex);
}
return 'Finished!';
});
// Execute program() and print the result.
program()(function (err, result) {
console.log(result);
});
node --version
v4.2.4
mac os yosemite
tested on both npm asyncawait and manually downloaded from github
........ so here what we see is that try..catch block does not work at all for exceptions thrown from parallelThreadAsync.
zero...
1
1
2
2
Caught an error [Error: sfdfsfds]
Finished!
Unhandled rejection Error: sfdfsfds
at parallelThreadFunc (/somedir/asyncawait-probable-bug.js:16:11)
at tryBlock (/somedir/node_modules/asyncawait/src/async/fiberManager.js:39:33)
at runInFiber (/somedir/node_modules/asyncawait/src/async/fiberManager.js:26:9)
Unhandled rejection Error: sfdfsfds
at parallelThreadFunc (/somedir/asyncawait-probable-bug.js:16:11)
at tryBlock (/somedir/node_modules/asyncawait/src/async/fiberManager.js:39:33)
at runInFiber (/somedir/node_modules/asyncawait/src/async/fiberManager.js:26:9)
Registry url: https://registry.npmjs.org/
Current Time: 28.05.2015 18:35:03
Last Refreshed: 14.05.2015 19:40:52
Number of Results: 157348
====Executing command 'npm install asyncawait --save '====
npm WARN package.json [email protected] No repository field.
[email protected] install C:\Users\Jenok\Documents\Visual Studio 2013\Projects\NodejsWebApp3\NodejsWebApp3\node_modules\asyncawait\node_modules\fibers
node ./build.js
child_process: customFds option is deprecated, use stdio instead.
C:\Users\Jenok\Documents\Visual Studio 2013\Projects\NodejsWebApp3\NodejsWebApp3\node_modules\asyncawait\node_modules\fibers>if not defined npm_config_node_gyp (node "C:\nodejs\node_modules\npm\bin\node-gyp-bin....\node_modules\node-gyp\bin\node-gyp.js" rebuild --release ) else (rebuild --release )
gyp ERR! configure error
gyp ERR! stack Error: Can't find Python executable "python", you can set the PYTHON env variable.
gyp ERR! stack at failNoPython (C:\nodejs\node_modules\npm\node_modules\node-gyp\lib\configure.js:103:14)
gyp ERR! stack at C:\nodejs\node_modules\npm\node_modules\node-gyp\lib\configure.js:64:11
gyp ERR! stack at FSReqWrap.oncomplete (evalmachine.:95:15)
gyp ERR! System Windows_NT 6.1.7601
gyp ERR! command "node" "C:\nodejs\node_modules\npm\node_modules\node-gyp\bin\node-gyp.js" "rebuild" "--release"
gyp ERR! cwd C:\Users\Jenok\Documents\Visual Studio 2013\Projects\NodejsWebApp3\NodejsWebApp3\node_modules\asyncawait\node_modules\fibers
gyp ERR! node -v v0.12.2
gyp ERR! node-gyp -v v1.0.3
gyp ERR! not ok
Build failed
npm ERR! Windows_NT 6.1.7601
npm ERR! argv "C:\nodejs\node.exe" "C:\nodejs\node_modules\npm\bin\npm-cli.js" "install" "asyncawait" "--save"
npm ERR! node v0.12.2
npm ERR! npm v2.7.4
npm ERR! code ELIFECYCLE
npm ERR! [email protected] install:node ./build.js
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] install script 'node ./build.js'.
npm ERR! This is most likely a problem with the fibers package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR! node ./build.js
npm ERR! You can get their info via:
npm ERR! npm owner ls fibers
npm ERR! There is likely additional logging output above.
npm ERR! Please include the following file with any support request:
npm ERR! C:\Users\Jenok\Documents\Visual Studio 2013\Projects\NodejsWebApp3\NodejsWebApp3\npm-debug.log
====npm command completed with exit code 1====
How i can catch an exception in await
block?
For example:
var songs = Await(global.db.collection('music')
.find(query, {
_id : 0,
name : 1,
artist : 1,
url : 1
})
.sort({ order : 1 })
.skip((isNaN(Number(skip))) ? 0 : Number(skip))
.toArray()
);
If i don't have collection music
or i get bad data, how i can catch exception in here?
The following pattern doesn't work. Is there any supported way to assign async methods to an ES6 class instance?
class API {
constructor(options) { }
async test() {
let test = await this.get('test')
console.log(test)
}
}
When an error occurs in an async
function, instead of throwing an error it just logs a message to the console (or that's what it seems like to me at least). Mocha doesn't register this error, and just waits until the timeout of 2000ms instead of failing immediately like it would in a non-async function. I think there needs to be some way to have it throw errors like it would traditionally so it works with Mocha and other similar unit testing frameworks instead of what it does currently.
The link in the README.md is broken. I believe the actual link was moved to here. The typed file could also be made available on TSD for easy access.
I am trying to make this work using the new classes and class method syntax in ecmascript 6, but it doesnt seem to work at all, the methods just never returns anything. Does this not yet support ecmascript 6 classes or is there a way I can make this work?
tell me how rewrite this function with the expectation?
var titles = GetTitles();
///....
function GetTitles() {
var titles;
connection.query('SELECT * FROM titles', function (err, rows) {
titles = rows;
});
return titles;
}
I would like to wait for the result C#
var titles = await GetTitles();
///....
function async GetTitles() { ///.... }
Hello!
Can you provide examples written on TypeScript ?
I try do it, but get "types" errors when compile code.
Thanks
I have the following basic code
'use strict'
const async = require('asyncawait/async');
const await = require('asyncawait/await');
const got = require('got')
async function mytest () {
const options = {}
let response = await got.get('https://www.google.com', options)
console.log(response)
}
mytest()
This uses the got httprequest library to pull a webpage and print out the response. I get the following error:
async function requestNewAccessToken2 (ocapi) {
^^^^^^^^
SyntaxError: Unexpected token function
at Object.exports.runInThisContext (vm.js:76:16)
at Module._compile (module.js:528:28)
at Object.Module._extensions..js (module.js:565:10)
at Module.load (module.js:473:32)
at tryModuleLoad (module.js:432:12)
at Function.Module._load (module.js:424:3)
at Module.runMain (module.js:590:10)
at run (bootstrap_node.js:394:7)
at startup (bootstrap_node.js:149:9)
at bootstrap_node.js:509:3
I feel like there is some basic thing I'm misunderstanding here. I'm using Node 6.7.0. But the asyncawait
library should work fine in this version right?
So I'd promisify fs
using bluebird.
var fs = Promise.promisifyAll(require("fs"));
Then use fs.existsAsync
, the promise version.
var chargebeeExists = await(fs.existsAsync(chargebeePath));
fs.exists
/ fs.existsAsync
returns one callback argument a bool based on if a file exists or not. Because it's in the normal node-callback error argument place, I'm getting this error Possibly unhandled Error: true
. Is there a way to circumvent this?
How can I enable asyncawait on eslint? babel-eslint
doesn't seem to work.
The README states:
node-fibers: This implementation of coroutines is unfortunately limited to Node.js. ES6 generators may be simpler, but fibers are more flexible and support a far broader space of design possibilities. It would be great if ES6 generators were this open and flexible.
and I got intrigued. What kind of things can Fibers do that Coroutines can't?
Thank you!
The following piece of code is what I am trying.
"use strict";
const Async = require("asyncawait/async");
const Await = require("asyncawait/await");
const State = require("./../models/state.js");
const bot = {
setFn(what) {
console.log(what);
},
receive: Async((obj) => {
console.log(this, obj);
this.setFn(obj);
let state = Await(State.find("zzzz")); //returns promise
return state;
})
};
bot.receive({a: 1});
This snippet when run throws the following exception:
Unhandled rejection TypeError: this.setFn is not a function
at Object.bot.receive (tests/asyncawait.js:11:14)
at tryBlock (node_modules/asyncawait/src/async/fiberManager.js:39:33)
at runInFiber (node_modules/asyncawait/src/async/fiberManager.js:26:9)
What am I doing wrong? When I printed this
it just printed empty object. Documentation mentions that the this
context is preserved. But seems like it is lost.
Can anyone help on this?
I'm attempting to write a VSCode extension that utilizes Bluebird and asyncawait. Here are my dependencies:
"dependencies": {
"asyncawait": "^1.0.6",
"bluebird": "^3.4.6",
"copy-paste": "^1.3.0",
"open": "0.0.5",
"request": "^2.74.0"
}
Here is some code of where I'm requiring it:
'use strict';
...
const async = require('asyncawait/async');
const await = require('asyncawait/await');
const Promise = require('bluebird');
...
When I attempt to run my extension, I get the following error:
Activating extension `MyLaptop.vscode-myextension` failed: `/Users/user1/Repos/vscode-myextension/node_modules/fibers/bin/darwin-x64-v8-4.9/fibers.node` is missing. Try reinstalling `node-fibers`?.
Activating extension `MyLaptop.vscode-myextension` failed: `/Users/user1/Repos/vscode-myextension/node_modules/fibers/bin/darwin-x64-v8-4.9/fibers.node` is missing. Try reinstalling `node-fibers`?
Here is the error stack: Error: `/Users/user1/Repos/vscode-myextension/node_modules/fibers/bin/darwin-x64-v8-4.9/fibers.node` is missing. Try reinstalling `node-fibers`?
at Object.<anonymous> (/Users/user1/Repos/vscode-myextension/node_modules/fibers/fibers.js:16:8)
at Module._compile (module.js:413:34)
at Object.Module._extensions..js (module.js:422:10)
at Module.load (module.js:357:32)
at Function.Module._load (module.js:314:12)
at Function.L.I.n._load (/Applications/Visual Studio Code.app/Contents/Resources/app/out/vs/workbench/node/extensionHostProcess.js:12:25921)
at Module.require (module.js:367:17)
at require (internal/module.js:16:19)
at Object.<anonymous> (/Users/user1/Repos/vscode-myextension/node_modules/asyncawait/src/fibers.js:1:92)
at Module._compile (module.js:413:34)
I tried intentionally uninstalling and reinstalling fibers:
user1@User1:~/Repos/vscode-myextension
# npm uninstall fibers
- [email protected] node_modules/fibers
npm WARN EPACKAGEJSON [email protected] No repository field.
npm WARN EPACKAGEJSON [email protected] No license field.
user1@User1:~/Repos/vscode-myextension
# npm install fibers
> [email protected] install /Users/user1/Repos/vscode-myextension/node_modules/fibers
> node build.js || nodejs build.js
`darwin-x64-v8-4.6` exists; testing
Binary is fine; exiting
[email protected] /Users/user1/Repos/vscode-myextension
└── [email protected]
npm WARN EPACKAGEJSON [email protected] No repository field.
npm WARN EPACKAGEJSON [email protected] No license field.
user1@User1:~/Repos/vscode-myextension
#
But I get the same error. Am I missing something here? Is this a node fiber issue?
Hi,
I need help, I'm using this library and this is an example with the problem that I've encountered:
// message is an object not used in this example, uri is the download url (http://site.com/file.png), name is the candidate name of save
var foo = async(function(message, uri, name) {
var validName = await(checkFile(name)); <-- the function checkFile checks the candidate name and change it if already used on the disk.
console.log("valid name: " + validName); <-- a print just to check, yes, the var "validName" is ok, contains the new name of the file.
var downloadedName = await(downloadFile(uri, validName)); <-- the function downloadFile download the file from the url and save it with the new name.
console.log("Downloaded name: " + downloadedName); <-- the var downloadedName isn't up to date, print undefined.
return true; <-- don't care, it's just a test.
});
This is the function downloadFile:
function downloadFile(uri, filename) {
console.log("[downloadFile] definitiveName: " + filename); <--- print correctly the definitive name
request(uri).pipe(fs.createWriteStream(filesFolder + filename)).on('close', function(err){
if(err) throw console.log(err);
else {
console.log("[downloadFile] Downloaded: " + filename); <--- print correctly the definitive name
return filename; <-- the return of the function
}
});
}
What happen in console:
Valid name: theNameOfTheFile.png
[downloadFile] definitiveName: theNameOfTheFile.png
Downloaded name: undefined
[downloadFile] Downloaded: theNameOfTheFile.png
The question is: why the second await() doesn't wait the end and return of the function?
Regards.
hello - (newbie here)
having become an excellent code "indentor" with multiple nested async functions, i am most eager to try out asyncawait.
i attempted to do a simple install as per the instructions i read:
npm install asyncawait ;
and here is my error log below - i read where it said to contact the author - i hope this is the correct forum.
http://edwardsmark.com/asyncawaitIssue/npm-debug.log
alias nodejs=node ;
nodejs -v
v4.2.3
npm -v
2.5.1
npm owner ls fibers
laverdet [email protected]
thank you very much.
Any plans? =)
Hey guys.
I have a question. I was able to successfully use await with thenable
objects, works great!
But now I have the following simple function:
function getResults(callback){
callback([my, results, here]];
}
How can I make this work with asyncawait while mantaining backwards compatibility? I tried:
var getResults = async.cps(function getResults(callback){
callback([my, results, here]];
})
and then called await(getResults())
, but it didn't work. Is this possible?
Great work by the way!
I have some code (3rd-party that I can't change) that calls a function to get some data
var x = lib.myFoo(id)
---
lib.js
function myFoo(id) {
return data[id];
}
where data is an object holding a set of objects. I can modify lib.js
I need to convert the objects to a database call, so I've been trying to use generators to do this
function myFoo(id) {
var data = main(id);
data.next();
function *main(id) {
var result = yield getId(id);
return result;
}
function getId(id) {
myDB.find(id,function(err,result) {
data.next(result);
});
}
};
but I cannot get it working. Basically I am looking to get the ES7 await style functionality - ie
function myFoo(id) {
var x = await SomeAsyncFunction()
return x;
}
is this possible ?
Hi,
I am having trouble converting these functions into asyncawait.
function doesUserHaveAsscess(user) {
var receiptsTable = tables.getTable('receipts');
// lets find all of this users receipts first
receiptsTable.where({ userId: user.userId }).read({
success: function(results) {
if (results.length > 0) {
// check that we have a valid receipt for this user
for (var i = 0; i < results.length; i++) {
if (checkIsValid(results[i])) {
return true;
}
}
}
// no valid receipts found - time to pay up
return false;
}
});
}
function checkIsValid(receipt) {
var receiptDate = new Date(parseInt(receipt.purchaseDateMs, 10));
var durations = {
'com.foo.weekly': day * 7,
'com.foo.monthly': day * 31
};
var expiry = receiptDate.getTime() + durations[receipt.productId];
var expiryDate = new Date(expiry);
var now = new Date();
console.log(now < expiryDate, now, expiryDate);
return now < expiryDate;
}
Thanks,
Attiqe
I am trying to use it on node-webkit (nw.js) but when I import it. it throws an error
my code.
var async = require('asyncawait/async'); var await = require('asyncawait/await');
Here is the error
module.js:482 Uncaught Error: A dynamic link library (DLL) initialization routine failed.
\?\E:\ZeroKit\webkit-v0.13\ZeroKitFinal\node_modules\fibers\bin\win32-x64-48\fibers.node
I have the following asynchronous function which uses Mongoose:
exports.add = (body, success_callback, error_callback) ->
Team = models('Team')
team = new Team body
team.save (error, team) ->
if error || !team
error_callback error
else
success_callback team
And I'm attempting to use it with asyncawait in the following fashion, using bluebird's promisifyAll() as recommended:
exports.sample = (values, callback) ->
ret = {}
run = async ->
console.log 'async'
if values.team?.length?
team_controllers = Promise.promisifyAll require '../../modules/team/controllers.js'
ret.team = []
for team_values in values.team
ret.team.push await team_controllers.addAsync(
team_values
, (team) ->
console.log team # This outputs
team
)
ret
run().then (ret) ->
console.log 'then' # This never runs
callback ret
It seems as though the success_callback is executing, as I see the console.log team
output. However the code provided to async.then()
never runs.
If I change the await()
argument to a synchronous function or value, then async.then()
runs as expected.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.