https://github.com/akamaozu/cjs-yield
Don't Start Function Until Current Callstack Ends
https://github.com/akamaozu/cjs-yield
async concurrency cooperative non-blocking yield
Last synced: 4 months ago
JSON representation
Don't Start Function Until Current Callstack Ends
- Host: GitHub
- URL: https://github.com/akamaozu/cjs-yield
- Owner: Akamaozu
- Created: 2018-11-04T13:19:15.000Z (almost 7 years ago)
- Default Branch: master
- Last Pushed: 2019-01-03T04:24:39.000Z (almost 7 years ago)
- Last Synced: 2025-03-10T04:08:56.381Z (7 months ago)
- Topics: async, concurrency, cooperative, non-blocking, yield
- Language: JavaScript
- Homepage:
- Size: 28.3 KB
- Stars: 0
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
Yield
===
[](https://badge.fury.io/js/cjs-yield) [](https://travis-ci.org/Akamaozu/cjs-yield) [](https://coveralls.io/github/Akamaozu/cjs-yield?branch=master)Don't Start Function Until Current [Callstack](https://www.youtube.com/watch?v=8aGhZQkoFbQ&feature=youtu.be&t=256) Ends
---### Install
```
npm install --save cjs-yield
```### How It Works
#### Call Function Normally
```js
say_hi();
console.log( 'callstack ends' );// output
// > Hi!
// > callstack ends
```#### Yield Function Call
```js
var _yield = require( 'cjs-yield' );_yield( say_hi );
console.log( 'callstack ends' );// output
// > callstack ends
// > Hi!
```#### Pass Yielded Function Arguments
```js
_yield( say_hi, 'Dr. Nick' );
console.log( 'callstack ends' );// output
// > callstack ends
// > Hi Dr. Nick!
``````js
_yield( say_hi, 'Archie', 'the Drells' );
console.log( 'callstack ends' );// output
// > callstack ends
// > Hi Archie and the Drells!
``````js
_yield( say_hi, 'Ed', 'Edd', 'Eddy' );
console.log( 'callstack ends' );// output
// > callstack ends
// > Hi Ed, Edd and Eddy!
```### Gotchas
#### 1. Yield DOES NOT work with functions that internally use `this`
Internally, yield uses `setTimeout.apply` to yield a given function, while making it easy to pass arguments to it. To make the API as simple and as pleasant as posible, `setTimeout.apply` uses null as its default context. This is fine unless the function use `this` keyword internally. Even if you avoid writing functions that use `this`, you can't escape it since many native JavaScript array methods like `Array.push` use it.
To yield a function that uses `this`, put the troublesome function into a function that doesn't use `this` and pass that new function to yield.
Eg.
```js
var heroes = [];
_yield( heroes.push, 'Batman' );
console.log( 'callstack ends' );// > callstack ends
// > heroes=[]
```vs
```js
var heroes = [];
_yield( add_hero, 'Batman' );
console.log( 'callstack ends' );// > callstack ends
// > heroes=[ 'Batman' ]function add_hero( name ){
heroes.push( name );
}
```