Skip to content

Instantly share code, notes, and snippets.

@filipebarcos
Last active May 13, 2017 12:20
Show Gist options
  • Save filipebarcos/0a137d6ca837c117f999958a365fc5b6 to your computer and use it in GitHub Desktop.
Save filipebarcos/0a137d6ca837c117f999958a365fc5b6 to your computer and use it in GitHub Desktop.
Code Snippets for my CEJS 2017 Talk
function* foo(x) {
const y = 2 * (yield (x + 1));
const z = yield (y / 3);
return (x + y + z);
}
var it = foo( 5 );
// note: not sending anything into `next()` here
console.log(it.next()); // { value:6, done:false }
console.log(it.next(12)); // { value:8, done:false }
console.log(it.next(13)); // { value:42, done:true }
import { call, put } from 'redux-saga/effects';
export function* fetchData(action) {
  try {
    const data = yield call(Api.fetchUser, action.payload.url);
    yield put({type: 'FETCH_SUCCEEDED', data});
  } catch (error) {
    yield put({type: 'FETCH_FAILED', error});
  }
}
function* watchFetchData() {
  yield takeEvery('FETCH_REQUESTED', fetchData);
}
import { takeEvery } from 'redux-saga';
// FETCH_USERS
function* fetchUsers(action) { ... }
// CREATE_USER
function* createUser(action) { ... }
// use them in parallel
export default function* rootSaga() {
yield takeEvery('FETCH_USERS', fetchUsers);
yield takeEvery('CREATE_USER', createUser);
}
{
CALL: {
fn: Api.fetchUser,
args: [“/users”],
},
}
const generator = fetchData();
expect(generator.next()).toEqual({
done: false,
value: call(Api.fetchUser, action.payload.url)
});
function* watchThis() {
  yield takeEvery('THIS', doThat);
}
function* watchThis() {
while(true) {
yield take('THIS', doThat);
}
}
function* watchDeaths() {
yield take('DIE', newTry);
yield take('DIE', newTry);
yield take('DIE', put, { type: 'GAME_OVER' });
}
function* mySaga() {
while(true) {
yield take('baz');
yield call(foo);
yield call(bar);
}
}
function* mySaga() {
while(true) {
yield take('baz');
yield fork(foo);
yield fork(bar);
}
}
const [visits, registrations] = yield all([
call(fetch, '/visits'),
call(fetch, '/registrations')
]);
const { posts, timeout } = yield race({
posts: call(fetch, '/posts'),
timeout: call(delay, 1000)
});
function* mySync() {
try {
while(true) {
yield put({type: 'SYNC_STARTED'});
const result = yield call(syncMyFiles);
yield call(delay, 500);
}
} finally {
if (yield cancelled())
yield put({ type: 'SYNC_STOPED'});
}
}
function* myDropbox() {
while(yield take('START_FILE_SYNC')) {
const mySyncTask = yield fork(mySync);
yield take('STOP_FILE_SYNC');
// this will cause the forked task to jump into its finally block
yield cancel(mySyncTask);
}
}
function* foo() { ... }
function* bar() { ... }
function* baz() { ... }
function* fooBarBaz() {
yield* foo();
yield* bar();
yield* baz();
}
// vs.
function* fooBarBaz() {
yield* call(foo);
yield* fork(bar);
yield* call(baz);
}
@filipebarcos
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment