Skip to content

Commit

Permalink
chroe: add more comments for toAsyncFunction and toPromise
Browse files Browse the repository at this point in the history
  • Loading branch information
Maledong authored and dead-horse committed Aug 27, 2018
1 parent 4d4113c commit ae38fa4
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 8 deletions.
32 changes: 26 additions & 6 deletions lib/egg.js
Original file line number Diff line number Diff line change
Expand Up @@ -351,9 +351,20 @@ class EggCore extends KoaApplication {
}

/**
* use co to wrap generator function to a function return promise
* @param {GeneratorFunction} fn input function
* @return {AsyncFunction} async function return promise
* Convert a generator function to a promisable one.
*
* Notice: for other kinds of functions, it directly returns you what it is.
*
* @param {Function} fn The inputted function.
* @return {AsyncFunction} An async promise-based function.
* @example
* ```javascript
* const fn = function* (arg) {
return arg;
};
const wrapped = app.toAsyncFunction(fn);
wrapped(true).then((value) => console.log(value));
* ```
*/
toAsyncFunction(fn) {
if (!is.generatorFunction(fn)) return fn;
Expand All @@ -364,9 +375,18 @@ class EggCore extends KoaApplication {
}

/**
* use co to wrap array or object to a promise
* @param {Mixed} obj input object
* @return {Promise} promise
* Convert an object with generator functions to a Promisable one.
* @param {Mixed} obj The inputted object.
* @return {Promise} A Promisable result.
* @example
* ```javascript
* const fn = function* (arg) {
return arg;
};
const arr = [ fn(1), fn(2) ];
const promise = app.toPromise(arr);
promise.then(res => console.log(res));
* ```
*/
toPromise(obj) {
return co(function* () {
Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@
"types": "index.d.ts",
"scripts": {
"autod": "autod",
"lint": "eslint lib test *.js",
"test": "npm run lint && egg-bin test",
"lint": "eslint .",
"test": "npm run lint -- --fix && egg-bin test",
"test-local": "egg-bin test",
"cov": "egg-bin cov",
"pkgfiles": "egg-bin pkgfiles",
Expand Down
6 changes: 6 additions & 0 deletions test/egg.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -415,6 +415,12 @@ describe('test/egg.test.js', () => {
const wrapped = app.toAsyncFunction(fn);
return wrapped(true).then(res => assert(res === true));
});

it('not translate common values', () => {
const primitiveValues = [ 1, 2, 3, 4, 5, 6 ];
const wrapped = app.toAsyncFunction(primitiveValues);
return assert(wrapped === primitiveValues);
});
});

describe('toPromise', () => {
Expand Down

0 comments on commit ae38fa4

Please sign in to comment.