Security News
GitHub Removes Malicious Pull Requests Targeting Open Source Repositories
GitHub removed 27 malicious pull requests attempting to inject harmful code across multiple open source repositories, in another round of low-effort attacks.
async-to-gen
Advanced tools
Transform async functions to generator functions with speed and simplicity.
Turn your JavaScript with async functions into ES6 generators so they can be used in modern browsers or in node.js (v0.12 or newer).
Async functions are an exciting new proposed addition to JavaScript. The v8 team is hard at work getting it right, which means it could appear in future versions of node.js. However if you're impatient like me, then you probably just can't wait to get rid of your promise triangles and callback hell.
You can use Babel to accomplish this, but async-to-gen
is a faster, simpler, zero-configuration alternative with minimal dependencies
for super-fast npm install
and transform time.
Also, async-to-gen
provides support for async generators
which return Async Iterators, a great syntax and primitive for producing and
operating on streams of data.
Use the command line:
npm install --global async-to-gen
async-to-gen --help
async-to-gen input.js > output.js
Or the JavaScript API:
npm install async-to-gen
var asyncToGen = require('async-to-gen');
var fs = require('fs');
var input = fs.readFileSync('input.js', 'utf8');
var output = asyncToGen(input).toString();
fs.writeFileSync('output.js', output);
// source maps!
var map = asyncToGen(input, { sourceMaps: true }).generateMap();
fs.writeFileSync('output.js.map', output);
async-node
Wherever you use node
you can substitute async-node
and have a super fast
async functions aware evaluator or REPL.
$ async-node
> async function answer() {
... return await 42
... }
undefined
> promise = answer()
Promise { <pending> }
> promise.then(console.log)
Promise { <pending> }
42
Using the require hook allows you to automatically compile files on the fly when requiring in node:
require('async-to-gen/register')
require('./some-module-with-async-functions')
Rollup: rollup-plugin-async
Async functions are great for writing asynchronous code that looks synchronous, and that's perfect for writing code that needs to perform async I/O operations.
One of the original motivations for Node.js was non-blocking I/O, perfect! However its core libraries do not yet support Promises, nor do many popular libraries written for Node 😭.
Do not fret, we can fix this with promisify-node!
const promisify = require('promisify-node');
const fs = promisify('fs');
async function emojify(filePath) {
const contents = await fs.readFile(filePath, 'utf8')
const edited = contents.replace(/:\)/g, '😉')
await fs.writeFile(filePath, edited, 'utf8')
}
Writing tests in mocha? Async functions are super handy for testing any code using promises and already work out of the box! To enable async functions in mocha include the require hook when you run your tests:
mocha --require async-to-gen/register test.js
Then in your tests, use async functions in your it
clauses:
describe('My Promising Module', () => {
it('promises to give a value', async () => {
expect(await myFunction('input')).to.equal('output')
})
})
Testing your express app? Try supertest-as-promised and async functions:
const express = require('express')
const request = require('supertest-as-promised')
const app = express()
app.get('/foo', (req, res) => res.send('bar'))
describe('My express app', () => {
it('loads foo', async () => {
const response = await request(app).get('/foo')
expect(response).to.equal('bar')
})
})
Writing tests in Jest? Use the scriptPreprocessor entry in your jest configuration in package.json:
{
"name": "my-project",
"jest": {
"scriptPreprocessor": "async-to-gen"
},
"devDependencies": {
"async-to-gen": "*"
}
}
Have interactive scripts that require lots of input from the user? Async functions make writing those much easier! Check out interactive-script.
npm install interactive-script
Then write your script:
const interactive = require('interactive-script')
interactive(async (say, ask) => {
say('What is your favorite number?')
let num;
do {
num = Math.ceil(Math.random() * 100)
} while (!await ask(`Is it ${num}? `, 'yN'))
say(`Great, I think ${num} is a fine number.`)
})
And run it with async-node
:
async-node myScript.js
Streaming data can be a challenging thing to get right. While Observables have provided a great library for streamed data, Async Generators provides language-level support for this concept!
Consider subscribing to a web socket within an program using async functions:
async function* stockTickerInEuro(symbol) {
var socket = await openWebSocket('ws://stocks.com/' + symbol)
try {
for await (var usd of socket) {
var euro = usd * await loadExchangeRateUSD2EUR()
yield euro
}
} finally {
closeWebSocket(socket)
}
}
Then calling this function produces an Async Iterator (an Iterator of Promises) of stock ticker values.
var ticker = stockTickerInEuro('AAPL')
ticker.next().then(step => console.log(step.value))
Or use for-await
loops within another async function:
async function bloombergTerminal() {
for await (var price of stockTickerInEuro('AAPL')) {
console.log(price)
}
}
NOTE: The behavior of for-await
loops using this tool is not identical to the
proposed spec addition. Where the proposed spec's for-await
expects a
Symbol.asyncIterator
method for the iterated source, this tool expects
Symbol.iterator
instead since it transforms it to a for-of
loop.
When async-to-gen
transforms async functions, it makes as few edits as
possible, and does not affect the location of lines in a file, leading to easier
to understand stack traces when debugging.
It also includes a very small conversion function at the bottom of the file. How small? 217 chars for async functions and 533 chars for async generators.
Before:
async function foo() {
return await x
}
After:
function foo() {return __async(function*(){
return yield x
}())}
function __async(g){/* small helper function */}
Don't bother using both! If you're already using Babel (maybe you need JSX,
other proposed features, or are supporting older versions of Node) then you
might be excited to hear that using babel-preset-es2017
in your .babelrc
will provide support for async functions!
Babel is an amazing tool that you should consider using, however async-to-gen
intentionally makes some different choices to provide a different set of
trade-offs. Babel is general-purpose and supports a wider set of features but
requires some configuration and more dependencies and those features may cost
build performance or output code quality. async-to-gen
can only do one thing,
but that simplicity lends itself towards faster builds and cleaner output.
Ultimately, if you only need to add async function support you should try
async-to-gen
but if you need more features then you should use Babel.
FAQs
Transform async functions to generator functions with speed and simplicity.
The npm package async-to-gen receives a total of 10,458 weekly downloads. As such, async-to-gen popularity was classified as popular.
We found that async-to-gen demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
GitHub removed 27 malicious pull requests attempting to inject harmful code across multiple open source repositories, in another round of low-effort attacks.
Security News
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.
Security News
Node.js will be enforcing stricter semver-major PR policies a month before major releases to enhance stability and ensure reliable release candidates.