koa-ctx
Get koa ctx anywhere. By @superjs
async/await way to call callback style functions
Thought
If you want to convert callback style to async/await style, you can either:
- wrap the operation to return a new Promise, which is ugly
- or, just call the operation, using @superjs/cb as callback, then await the cb
Example
const Cb = // await can't be used without being wrapped by async function;async { // Cb() create a plain Promise // with some extra fields/magics await Cb}
You can also use it as event handlers:
const Cb = const spawn = // await can't be used without being wrapped by async function;async { let proc = // Cb().ok resolve 1st arg procstdout // use Cb instead of Cb() to reference the last created one proc //Cb.err reject 1st arg try let out = await Cb console catch err console }
API
Cb()
returns
:Cb
, return itself
calling Cb
will create a Promise
: cb
, then push cb
to cbStack
.
From now on, Cb
will ref to the cb
created
ref means you can use Cb.ok/err/arr/pair
to get cb.ok/err/arr/pair
Cb.pop()
returns
:cb
, aPromise
Pop the top cb
in cbStack
and return it
Cb.new()
returns
:cb
, aPromise
return a standalone cb not included by cbStack
comparing to Cb()/Cb.pop()
, you would have to add a local variable to reference to Cb.new()
cb.then/catch/finally
since cb is a Promise
, use them just like new Promise(...).then/catch/finally
cb.ok(value)
value
: value to be resolved with
resolve the Promise cb
with value
cb.err(err)
err
: error to be rejected with
reject the Promise cb
with err
cb.arr(...args)
...args
: arg list to be resolved with
collect args received as an array and resolve with args
cb.pair(err, value)
-
err
: error to be rejected with,err==null
to resolvevalue
-
value
: value to be resolved with, iferr==null
@superjs/wait
Use together with@superjs/wait can await something synchronously.
const Cb = const wait = // wait instead of awaitlet result = // print [3,-1] one second laterconsole { }
Compatibility
You can use @superjs/cb in both nodejs and browser environment.