• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

TypeScript effects.take函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了TypeScript中redux-saga/effects.take函数的典型用法代码示例。如果您正苦于以下问题:TypeScript take函数的具体用法?TypeScript take怎么用?TypeScript take使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了take函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的TypeScript代码示例。

示例1: watchDelete

function* watchDelete() {
  while (true) {
    const { id, formId } = yield take(DELETE_SUBMISSION);
    const { auth: { api } } = yield select();

    try {
      const [{ payload: { prevRowId } }] = yield [
        take(action => action.query === 'SUBMISSIONS' && action.type === ROW_REMOVED && action.payload.row.id === id),
        api.deleteSubmission(id),
      ];

      const { submissions } = yield select();

      if (prevRowId) {
        const nextRow = submissions.rows.get(submissions.rows.findIndex(row => row.id === prevRowId) + 1);

        var redirectTo = nextRow ? nextRow.id : prevRowId;
      } else {
        var redirectTo = submissions.rows.isEmpty() ? '' : submissions.rows.first().id;
      }

      yield put(routeActions.push(`forms/${formId}/submissions/${redirectTo}`));
    } catch(error) {
      console.log(error);
    }
  }
}
开发者ID:rosendi,项目名称:figure,代码行数:27,代码来源:submissions.ts


示例2: botSaga

export default function* botSaga(tankId: TankId) {
  const ctx = new Bot(tankId)
  try {
    yield takeEvery(hitPredicate, hitHandler)
    const result = yield race({
      service: all([
        generateBulletCompleteNote(),
        directionController(tankId, ctx.directionControllerCallback),
        fireController(tankId, ctx.fireControllerCallback),
        AIWorkerSaga(ctx),
      ]),
      killed: take(killedPredicate),
      endGame: take(A.EndGame),
    })
    const tank: TankRecord = yield select(selectors.tank, tankId)
    yield put(actions.setTankToDead(tankId))
    if (result.killed) {
      yield explosionFromTank(tank)
      if (result.killed.method === 'bullet') {
        yield scoreFromKillTank(tank)
      }
    }
    yield put(actions.reqAddBot())
  } finally {
    const tank: TankRecord = yield select(selectors.tank, tankId)
    if (tank && tank.alive) {
      yield put(actions.setTankToDead(tankId))
    }
  }

  function hitPredicate(action: actions.Action) {
    return action.type === actions.A.Hit && action.targetTank.tankId === tankId
  }

  function* hitHandler(action: actions.Hit) {
    const tank: TankRecord = yield select(selectors.tank, tankId)
    DEV.ASSERT && console.assert(tank != null)
    if (tank.hp > 1) {
      yield put(actions.hurt(tank))
    } else {
      const { sourceTank, targetTank } = action
      yield put(actions.kill(targetTank, sourceTank, 'bullet'))
    }
  }

  function killedPredicate(action: actions.Action) {
    return action.type === actions.A.Kill && action.targetTank.tankId === tankId
  }

  function* generateBulletCompleteNote() {
    while (true) {
      const { bulletId }: actions.BeforeRemoveBullet = yield take(actions.A.BeforeRemoveBullet)
      const { bullets }: State = yield select()
      const bullet = bullets.get(bulletId)
      if (bullet.tankId === tankId) {
        ctx.noteChannel.put({ type: 'bullet-complete', bullet })
      }
    }
  }
}
开发者ID:socoolxin,项目名称:battle-city,代码行数:60,代码来源:BotSaga.ts


示例3: fork

  yield fork(function* () {
    const { success } = yield race({ success: take(SIGNUP_SUCCESS), otherwise: take(SIGNUP_FAILURE) });

    if (success) {
      yield call(createToken, { email, password });
    }
  });
开发者ID:rosendi,项目名称:figure,代码行数:7,代码来源:auth.ts


示例4: fork

  yield fork(function*() {

    let prevState: ApplicationState;
    yield take(TRIED_LOADING_APP_STATE);

    while(true) {
      yield take();
      yield call(delay, PERSIST_DELAY_TIMEOUT);
      const state: ApplicationState = yield select();
      if (prevState === state) {
        continue;
      }

      prevState = state;

      // convert to a POJO object in case there are non serializable
      // object somehow in the application store. For the most part -- everything should be
      // a POJO with very few exceptions. For cases where data cannot be converted into a plain object, the application will need to re-hydrate the non-serializable data on startup. 
      const pojoState = serializeApplicationState(state);
      const { apiHost }: ApplicationState = state;

      yield call(fetch, apiHost + "/storage/" + state.storageNamespace + SAVE_KEY, {
        method: "POST",
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        } as any,
        body: JSON.stringify(pojoState)
      });
    }
  });  
开发者ID:cryptobuks,项目名称:tandem,代码行数:31,代码来源:api.ts


示例5: authFlow

export function* authFlow() {
  yield fork(watchStorage);
  yield fork(redirectOnAuth);

  while (true) {
    const token = auth.retrieveToken();

    if (token) {
      const state = yield select(state => state.auth);

      if (!state || state.token.toString() !== token.toString()) {
        yield put(signinSuccess(token, false));
      }

      yield call(watchExpiration, token.expiresIn);
    } else {
      yield call(purgeToken, false);
    }

    const { signin, signup } = yield race({ signin: take(SIGNIN), signup: take(SIGNUP), overwise: take(SIGNIN_SUCCESS) });

    if (signin) {
      yield fork(submitSigninForm, signin.resolve, signin.reject);
      yield call(createToken, signin);
      continue;
    }

    if (signup) {
      yield fork(submitSignupForm, signup.resolve, signup.reject);
      yield call(createUser, signup);
      continue;
    }
  }
}
开发者ID:rosendi,项目名称:figure,代码行数:34,代码来源:auth.ts


示例6: it

 it('should add recommendations page if recommendations were returned', () => {
     return expectSaga(recommendationsSaga(mockStoreApi))
         .withState({
             currentUser: {
                 status: 'LOGGED_IN',
                 token: '',
             },
             ignored: [],
             owned: [],
         })
         .provide([
             [call(mockStoreApi.getRecommendations, ''), { data: mockRecommendations }],
             [call(createScrollChannel), mockScrollChannel],
             [take(mockScrollChannel), mockScrollInfo299px],
             [matchers.call.fn(getRecommendationsPage), mockPage],
             [take(mockScrollChannel), mockScrollInfo299px],
             [matchers.call.fn(getRecommendationsPage), mockPage],
         ])
         .put(productActions.add(mockPage.products))
         .put(recommendationsActions.addPage(mockPage.items))
         .delay(100)
         .put(productActions.add(mockPage.products))
         .put(recommendationsActions.addPage(mockPage.items))
         .silentRun(150)
 })
开发者ID:steam-react,项目名称:steam,代码行数:25,代码来源:recommendations.test.ts


示例7: handleOpenTandem

function* handleOpenTandem() {
  yield take(OPEN_TANDEM_EXECUTED);

  let state: ExtensionState = yield select();
  var textDocumentContentProvider = {
    provideTextDocumentContent(uri) {
      return `
        <html>
          <head>
            <title>Tandem</title>
          </head>
          <body>
            <iframe src="${getIndexUrl(state)}" style="position:absolute;left:0;top:0;width:100vw; height: 100%; border: none;"></iframe>
          </body>
        </html>
      `;
    },
  };

  state.context.subscriptions.push(
    vscode.workspace.registerTextDocumentContentProvider(
      PREVIEW_NAME,
      textDocumentContentProvider)
  );

  while(true) {
    yield call(vscode.commands.executeCommand,
      "vscode.previewHtml",
      PREVIEW_URI,
      vscode.ViewColumn.Two,
      "Tandem"
    );
    yield take(OPEN_TANDEM_EXECUTED);
  }
}
开发者ID:cryptobuks,项目名称:tandem,代码行数:35,代码来源:vscode.ts


示例8: watchCreateAndRemoveLastPosition

// use channel to make sure every create/remove run one by one
function* watchCreateAndRemoveLastPosition(): SagaIterator {
  try {
    const createLastPositionChan: TakeableChannel<{}> = yield actionChannel(
      getType(lastPositionsCreator.createLastPosition)
    )
    const removeLastPositionChan: TakeableChannel<{}> = yield actionChannel(
      getType(lastPositionsCreator.removeLastPosition)
    )
    while (true) {
      const [createLastPositionAction, removeLastPositionAction]: [
        ReturnType<typeof lastPositionsCreator.createLastPosition> | void,
        ReturnType<typeof lastPositionsCreator.removeLastPosition> | void
      ] = yield race([take(createLastPositionChan), take(removeLastPositionChan)])

      if (createLastPositionAction) {
        yield call(createLastPosition, createLastPositionAction)
      }

      if (removeLastPositionAction) {
        yield call(removeLastPosition, removeLastPositionAction)
      }
    }
  } catch (err) {
    console.error(err)
  }
}
开发者ID:foray1010,项目名称:Popup-my-Bookmarks,代码行数:27,代码来源:saga.ts


示例9: loginFlow

export function* loginFlow() {
  window.beforeLogin = '/';
  let previousSession = null;
  yield take(LOCATION_CHANGE);
  while (true) { // eslint-disable-line no-constant-condition
    console.log('while true ', new Date());
    const session = authAgent.getSession();
    let location = yield select(makeSelectLocation());
    location = location.pathname;

    if (session !== null)
    {
      if (session !== previousSession) {
        yield put({type: AUTHENTICATED});
      }
      if (previousSession === null) {
        console.log('writing new session');
        previousSession = session;
      }
      console.log('Session:', session);
      if (location === '/login')
      {
        if (window.beforeLogin === '/login' || window.beforeLogin === '/logout')
          window.beforeLogin = '/';
        yield put(push(window.beforeLogin))
      }
      else
      {
        window.beforeLogin = location;
      }
      yield take(LOGOUT);
      try {
        yield call([authAgent,authAgent.logout]);
        yield put({type : LOGGED_OUT});
      }
      catch (e)
      {
        console.log('logout error!', e);
      }
    }
    else
    {
      if (location !== '/login') {
        window.beforeLogin = location;
        yield put(push('/login'));
      }
      const { login, password} = yield take(AUTH);

      try { //context call
        yield call([authAgent,authAgent.auth], login, password);
      }
      catch(e)
      {
        console.log('login error!',e);
      }

    }
  }
}
开发者ID:,项目名称:,代码行数:59,代码来源:


示例10: submitSigninForm

function* submitSigninForm(resolve, reject) {
  const { failure } = yield race({ success: take(SIGNIN_SUCCESS), failure: take(SIGNIN_FAILURE)});

  if (failure) {
    typeof failure.reason.message === 'object' ? reject(failure.reason.message) : reject({ _error: failure.reason.message });
  } else {
    resolve();
  }
}
开发者ID:rosendi,项目名称:figure,代码行数:9,代码来源:auth.ts


示例11: testTake

function* testTake(): SagaIterator {
  yield take();
  yield take('my-action');
  yield take((action: Action) => action.type === 'my-action');
  yield take(isMyAction);

  // typings:expect-error
  yield take(() => {});

  yield take(stringableActionCreator);

  yield take([
    'my-action',
    (action: Action) => action.type === 'my-action',
    stringableActionCreator,
    isMyAction,
  ]);

  // typings:expect-error
  yield take([() => {}]);

  yield takeMaybe([
    'my-action',
    (action: Action) => action.type === 'my-action',
    stringableActionCreator,
    isMyAction,
  ]);

  yield take(channel);

  yield takeMaybe(channel);
}
开发者ID:woota,项目名称:redux-saga,代码行数:32,代码来源:effects.ts


示例12: redirectOnAuth

function* redirectOnAuth() {
  while (true) {
    const { signin, logout } = yield race({ signin: take(SIGNIN_SUCCESS), logout: take(LOGOUT_SUCCESS)});

    if (signin) {
      signin.performRedirect && (yield put(routeActions.push(yield call(refererPath, '/'))));
    } else {
      logout.performRedirect && (yield put(routeActions.push('/signin')));
    }
  }
}
开发者ID:rosendi,项目名称:figure,代码行数:11,代码来源:auth.ts


示例13: main

  function* main() {
    while( yield take('START_BACKGROUND_SYNC') ) {
      // starts the task in the background
      const bgSyncTask = yield fork(bgSync)

      // wait for the user stop action
      yield take('STOP_BACKGROUND_SYNC')
      // user clicked stop. cancel the background task
      // this will throw a SagaCancellationException into the forked bgSync
      // task
      yield cancel(bgSyncTask)
    }
  }
开发者ID:HawkHouseIntegration,项目名称:DefinitelyTyped,代码行数:13,代码来源:redux-saga-tests.ts


示例14: refreshTagsDeal

export function* refreshTagsDeal(): any {
	while (true) {
		yield race({
			login: take(LOGIN_SUCCESS),
			addTag: take(ADD_WIKI_SPECTAG_SUCCESS),
			modifyTag: take(CHANGE_WIKI_SPEC_TAG_SUCCESS),
			delTag: take(DEL_WIKI_SPECTAG_SUCCESS),
		});

		// 触发查询
		yield put(queryTags());
	}
}
开发者ID:weiweiwitch,项目名称:third-lab,代码行数:13,代码来源:tags.ts


示例15: refreshSpecPostDeal

export function* refreshSpecPostDeal(): any {
	while (true) {
		const {change, move2NewTag} = yield race({
			change: take(CHG_WIKI_SPECPOST_SUCCESS),
			move2NewTag: take(MOVE_WIKI_POST_2_NEW_TAG_SUCCESS),
		});
		if (change) {
			yield put(querySpecPost(change.payload.id)); // 刷新特定文章
		} else if (move2NewTag) {
			yield put(querySpecPost(move2NewTag.payload.id)); // 刷新特定文章
		}

	}
}
开发者ID:weiweiwitch,项目名称:third-lab,代码行数:14,代码来源:posts.ts


示例16: handleTakingScreesnshots

function* handleTakingScreesnshots() {
  yield take(HEADLESS_BROWSER_LAUNCHED);
  while(true) {
    
    yield call(takeComponentScreenshot);

    const state: ApplicationState = yield select();

    // happens during a screenshot
    if (!state.shouldTakeAnotherScreenshot) {
      yield take([FILE_CONTENT_CHANGED, FILE_REMOVED]);
    }
  }
}
开发者ID:cryptobuks,项目名称:tandem,代码行数:14,代码来源:screenshots.ts


示例17: consoleLogSaga

export function* consoleLogSaga() {

  while(true) {
    const { log: { level: acceptedLevel, prefix }}: ConsoleLogState = (yield select()) || defaultState;
    let { text, level }: LogAction = (yield take(LogActionTypes.LOG));
    if (!(acceptedLevel & level)) continue;
    const log = {
      [LogLevel.DEBUG]: console.log.bind(console),
      [LogLevel.LOG]: console.log.bind(console),
      [LogLevel.INFO]: console.info.bind(console),
      [LogLevel.WARNING]: console.warn.bind(console),
      [LogLevel.ERROR]: console.error.bind(console)
    }[level];


    text = PREFIXES[level] + (prefix || "") + text;
    text = colorize(text);

    if (typeof window !== "undefined" && !window["$synthetic"]) {
      return styledConsoleLog(new AnsiUp().ansi_to_html(text));
    }

    log(text);
  }
}
开发者ID:cryptobuks,项目名称:tandem,代码行数:25,代码来源:console.ts


示例18: handleDependencyGraph

function* handleDependencyGraph() {
  while(true) {
    const action = yield take([WATCHING_FILES, FILE_CONTENT_CHANGED, FILE_REMOVED]);
    
    console.log("loading dependency graph");
    const state: ApplicationState = yield select();
    let graph: DependencyGraph = {};
    for (const fileCacheItem of state.fileCache) {
      if (!isPaperclipFile(fileCacheItem.filePath, state)) {
        continue;
      }
      const { diagnostics, graph: newGraph } = yield call(loadModuleDependencyGraph, fileCacheItem.filePath, {
        readFile: getReadFile(state)
      }, graph);


      if (diagnostics.length) {
        console.error(`Failed to load dependency graph for ${fileCacheItem.filePath}.`);
      }

      graph = newGraph;

    }
    yield put(dependencyGraphLoaded(graph));
    yield call(evaluatePreviews, graph, action.type === FILE_CONTENT_CHANGED ? (action as FileContentChanged).filePath : null);
  }
}
开发者ID:cryptobuks,项目名称:tandem,代码行数:27,代码来源:uri-watcher.ts


示例19: handleOpenedSyntheticWindow

function* handleOpenedSyntheticWindow() {
  const proxies = new Map<string, [SEnvWindowInterface, () => any]>();
  const createRenderer = createSyntheticDOMRendererFactory(document);

  function* updateProxy(window: SEnvWindowInterface, isNew: boolean) {
    const containsProxy = proxies.has(window.$id);
    let proxy: SEnvWindowInterface;
    let disposeMirror: () => any;
    if (!containsProxy) {
      proxy = window.clone();
      const position = window.screenLeft || window.screenTop ? { left: window.screenLeft, top: window.screenTop } : (yield call(getBestWindowPosition, window.browserId, (existingWindow: SyntheticWindow) => existingWindow.$id !== window.$id));

      proxy.moveTo(position.left, position.top);
      proxy.resizeTo(window.innerWidth, window.innerHeight);
      proxy.renderer = createRenderer(proxy);
      proxy.renderer.start();

      disposeMirror = () => {};
      yield put(syntheticWindowProxyOpened(proxy, undefined, isNew));
    } else {
      [proxy, disposeMirror] = proxies.get(window.$id);
    }

    disposeMirror();
    proxies.set(window.$id, [proxy, mirrorWindow(proxy, window)])
  };

  while(true) {
    const { instance, isNew } = (yield take(SYNTHETIC_WINDOW_OPENED)) as SyntheticWindowOpened;
    yield call(updateProxy, instance, isNew);
  }
}
开发者ID:cryptobuks,项目名称:tandem,代码行数:32,代码来源:synthetic-browser.ts


示例20: login

function* login(history: History, authApi: IAuthApi, usersApi: IUsersApi, credentials: TCredentials) {
    try {
        const { token }: { token: IToken } = yield race({
            token: call(authApi.login, credentials),
            logout: take(actions.logout.getType()),
        })

        if (token) {
            yield call(authApi.setAuthToken, token)
            const user = yield call(usersApi.getTokenOwner, token.value)
            yield put(actions.loginSuccess({
                token: token.value,
                login: user.login,
                userId: user.id,
                avatarUrl: user.avatarUrl,
                displayName: user.displayName
            }))
            return token
        } else {
            yield call(logout, authApi)
        }
    } catch (e) {
        yield call(authApi.removeAuthToken)
        yield put(actions.loginFailure(e))
        return null
    }
}
开发者ID:steam-react,项目名称:steam,代码行数:27,代码来源:auth.ts



注:本文中的redux-saga/effects.take函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
TypeScript effects.takeEvery函数代码示例发布时间:2022-05-25
下一篇:
TypeScript effects.spawn函数代码示例发布时间:2022-05-25
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap