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

TypeScript operators.timeout函数代码示例

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

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



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

示例1: get

 public get(
   query: Ha4usObjectQuery,
   aTimeout: number = 500
 ): Promise<IStatefulObject[]> {
   return this.$objects
     .observe(query)
     .pipe(
       mergeMap((aObject: Ha4usObject) => {
         return this.$states.observe(aObject.topic).pipe(
           timeoutWith(100, of({})),
           take(1),
           map((state: Ha4usMessage) => {
             delete state.topic
             delete state.match
             return {
               object: aObject,
               state: state,
             }
           })
         )
       }),
       bufferTime(aTimeout),
       timeout(aTimeout * 2)
     )
     .toPromise()
 }
开发者ID:ha4us,项目名称:ha4us.old,代码行数:26,代码来源:stateful-objects.service.ts


示例2: it

  it('file replacements work with watch mode', async () => {
    const overrides = {
      fileReplacements: [
        {
          replace: normalize('/src/meaning.ts'),
          with: normalize('/src/meaning-too.ts'),
        },
      ],
      watch: true,
    };

    let buildCount = 0;
    let phase = 1;

    const run = await architect.scheduleTarget(target, overrides);
    await run.output.pipe(
      timeout(30000),
      tap((result) => {
        expect(result.success).toBe(true, 'build should succeed');

        const fileName = normalize('dist/main.js');
        const content = virtualFs.fileBufferToString(host.scopedSync().read(fileName));
        const has42 = /meaning\s*=\s*42/.test(content);
        buildCount++;
        switch (phase) {
          case 1:
            const has10 = /meaning\s*=\s*10/.test(content);

            if (has42 && !has10) {
              phase = 2;
              host.writeMultipleFiles({
                'src/meaning-too.ts': 'export var meaning = 84;',
              });
            }
            break;

          case 2:
            const has84 = /meaning\s*=\s*84/.test(content);

            if (has84 && !has42) {
              phase = 3;
            } else {
              // try triggering a rebuild again
              host.writeMultipleFiles({
                'src/meaning-too.ts': 'export var meaning = 84;',
              });
            }
            break;
        }
      }),
      takeWhile(() => phase < 3),
    ).toPromise().catch(() => {
      throw new Error(`stuck at phase ${phase} [builds: ${buildCount}]`);
    });

    await run.stop();
  });
开发者ID:angular,项目名称:angular-cli,代码行数:57,代码来源:replacements_spec_large.ts


示例3: querySnapshots

 querySnapshots(parentObjectId: Uuid): Promise<Snapshot[]> {
     return this.querySnapshotsByParentId(parentObjectId)
         // Unsubscribe automatically after first response event arrives.
         .pipe(
             take(1),
             // Issue an Rx.TimeoutError if queryTimeoutMillis elapses without any emitted event.
             timeout(this.options["queryTimeoutMillis"]),
         )
         .toPromise();
 }
开发者ID:coatyio,项目名称:coaty-js,代码行数:10,代码来源:historian.mocks.ts


示例4: intercept

 intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
     let obs = of(true).pipe(
         tap(() => this.sharedService.requestStarted(req)),
         switchMap(() => next.handle(req)),
     );
     if (this.sharedService.httpTimeout) {
         obs = obs.pipe(timeout(this.sharedService.httpTimeout));
     }
     return obs.pipe(finalize(() => this.sharedService.requestFinished(req)));
 }
开发者ID:AlphaX-IBS,项目名称:raiden,代码行数:10,代码来源:raiden.interceptor.ts


示例5: observableDefer

 const getLicense$ = observableDefer(() => {
   const getLicense = keySystem.getLicense(message, messageType);
   return (castToObservable(getLicense) as Observable<TypedArray|ArrayBuffer|null>)
     .pipe(
       timeout(10 * 1000),
       catchError((error : unknown) : never => {
         if (error instanceof TimeoutError) {
           throw new EncryptedMediaError("KEY_LOAD_TIMEOUT",
             "The license server took more than 10 seconds to respond.", false);
         }
         if (error instanceof Error) {
           throw error;
         }
         throw new Error("An error occured when calling `getLicense`.");
       })
   );
 });
开发者ID:canalplus,项目名称:rx-player,代码行数:17,代码来源:handle_session_events.ts


示例6: switchMap

    switchMap(action => {
      const filepath = action.payload.filepath;

      return forkJoin(
        readFileObservable(filepath),
        statObservable(filepath),
        // Project onto the Contents API response
        (content: Buffer, stat: fs.Stats): contents.IContent =>
          createContentsResponse(filepath, stat, content)
      ).pipe(
        // Timeout after one minute
        timeout(60 * 1000),
        map((model: contents.IContent<"notebook">) => {
          if (model.type !== "notebook") {
            throw new Error(
              "Attempted to load a non-notebook type from desktop"
            );
          }
          if (model.content === null) {
            throw new Error("No content loaded for notebook");
          }

          return actions.fetchContentFulfilled({
            filepath: model.path,
            model,
            kernelRef: action.payload.kernelRef,
            contentRef: action.payload.contentRef
          });
        }),
        catchError((err: Error) =>
          of(
            actions.fetchContentFailed({
              filepath,
              error: err,
              kernelRef: action.payload.kernelRef,
              contentRef: action.payload.contentRef
            })
          )
        )
      );
    })
开发者ID:nteract,项目名称:nteract,代码行数:41,代码来源:loading.ts


示例7: codeCompleteObservable

export function codeCompleteObservable(
  channels: Channels,
  editor: CMI,
  message: JupyterMessage
) {
  const completion$ = channels.pipe(
    childOf(message),
    ofMessageType("complete_reply"),
    map(entry => entry.content),
    first(),
    map(expand_completions(editor)),
    timeout(15000) // Large timeout for slower languages; this is just here to make sure we eventually clean up resources
  );

  // On subscription, send the message
  return Observable.create((observer: Observer<any>) => {
    const subscription = completion$.subscribe(observer);
    channels.next(message);
    return subscription;
  });
}
开发者ID:kelleyblackmore,项目名称:nteract,代码行数:21,代码来源:complete.ts


示例8: it

  it('should show error when lazy route is invalid on watch mode AOT', async () => {
    host.writeMultipleFiles(lazyModuleFiles);
    host.writeMultipleFiles(lazyModuleImport);
    host.replaceInFile(
      'src/app/app.module.ts',
      'lazy.module#LazyModule',
      'invalid.module#LazyModule',
    );

    const logger = new TestLogger('rebuild-lazy-errors');
    const overrides = { watch: true, aot: true };
    const run = await architect.scheduleTarget(target, overrides, { logger });
    await run.output.pipe(
      timeout(15000),
      tap((buildEvent) => expect(buildEvent.success).toBe(false)),
      tap(() => {
        expect(logger.includes('Could not resolve module')).toBe(true);
        logger.clear();
        host.appendToFile('src/main.ts', ' ');
      }),
      take(2),
    ).toPromise();
    await run.stop();
  });
开发者ID:angular,项目名称:angular-cli,代码行数:24,代码来源:lazy-module_spec_large.ts


示例9: concatMap

    concatMap((action: actions.RestartKernel | actions.NewKernelAction) => {
      const state = state$.value;
      const oldKernelRef = action.payload.kernelRef;
      const notificationSystem = selectors.notificationSystem(state);

      if (!oldKernelRef) {
        notificationSystem.addNotification({
          title: "Failure to Restart",
          message: "Unable to restart kernel, please select a new kernel.",
          dismissible: true,
          position: "tr",
          level: "error"
        });
        return empty();
      }

      const oldKernel = selectors.kernel(state, { kernelRef: oldKernelRef });

      if (!oldKernelRef || !oldKernel) {
        notificationSystem.addNotification({
          title: "Failure to Restart",
          message: "Unable to restart kernel, please select a new kernel.",
          dismissible: true,
          position: "tr",
          level: "error"
        });

        // TODO: Wow do we need to send notifications through our store for
        // consistency
        return empty();
      }

      const newKernelRef = kernelRefGenerator();
      const initiatingContentRef = action.payload.contentRef;

      // TODO: Incorporate this into each of the launchKernelByName
      //       actions...
      //       This only mirrors the old behavior of restart kernel (for now)
      notificationSystem.addNotification({
        title: "Kernel Restarting...",
        message: `Kernel ${oldKernel.kernelSpecName ||
          "unknown"} is restarting.`,
        dismissible: true,
        position: "tr",
        level: "success"
      });

      const kill = actions.killKernel({
        restarting: true,
        kernelRef: oldKernelRef
      });

      const relaunch = actions.launchKernelByName({
        kernelSpecName: oldKernel.kernelSpecName,
        cwd: oldKernel.cwd,
        kernelRef: newKernelRef,
        selectNextKernel: true,
        contentRef: initiatingContentRef
      });

      const awaitKernelReady = action$.pipe(
        ofType(actions.LAUNCH_KERNEL_SUCCESSFUL),
        filter(
          (action: actions.NewKernelAction | actions.RestartKernel) =>
            action.payload.kernelRef === newKernelRef
        ),
        take(1),
        timeout(60000), // If kernel doesn't come up within this interval we will abort follow-on actions.
        concatMap(() => {
          const restartSuccess = actions.restartKernelSuccessful({
            kernelRef: newKernelRef,
            contentRef: initiatingContentRef
          });

          if (
            (action as actions.RestartKernel).payload.outputHandling ===
            "Run All"
          ) {
            return of(
              restartSuccess,
              actions.executeAllCells({ contentRef: initiatingContentRef })
            );
          } else {
            return of(restartSuccess);
          }
        }),
        catchError(error => {
          return of(
            actions.restartKernelFailed({
              error,
              kernelRef: newKernelRef,
              contentRef: initiatingContentRef
            })
          );
        })
      );

      return merge(of(kill, relaunch), awaitKernelReady);
    })
开发者ID:nteract,项目名称:nteract,代码行数:99,代码来源:kernel-lifecycle.ts


示例10: it

it('should enforce types of scheduler', () => {
  const o = of('a', 'b', 'c').pipe(timeout(5, 'foo')); // $ExpectError
});
开发者ID:jaychsu,项目名称:RxJS,代码行数:3,代码来源:timeout-spec.ts


示例11: concatMap

 concatMap(duration =>
   makeRequest(duration).pipe(
     timeout(2500),
     catchError(error => of(`Request timed out after: ${duration}`))
   )
开发者ID:zwvista,项目名称:SampleMisc,代码行数:5,代码来源:utility.service.ts


示例12: checkForUpdates

  async checkForUpdates() {
    if (this.checking) {
      return;
    } else {
      this.checking = true;
    }

    try {
      await this.platform.ready();
      await this.hasDeploy();

      const hasUpdate = await Promise.race([
        this.pro.deploy().check(),
        new Promise((_, reject) => setTimeout(reject, 8000)),
      ]);

      console.log(hasUpdate);
      if (hasUpdate !== 'true') {
        return false;
      }

      switch (this.network.type) {
        // Don't update if the network type is slow (it probably costs a little bit)
        case Connection.CELL:
        case Connection.CELL_2G:
        case Connection.CELL_3G:
        case Connection.UNKNOWN:
        case Connection.NONE:
          this.network
            .onchange()
            .pipe(take(1))
            .subscribe(() => {
              this.checkForUpdates();
            });
          return false;

        case Connection.WIFI:
        case Connection.CELL_4G:
        default:
          break;
      }

      await this.pro
        .deploy()
        .download()
        .pipe(
          tap(status => console.log('Download status:', status)),
          filter(status => status === 'true' || status === 'done'),
          switchMap(() => this.pro.deploy().extract()),
          tap(status => console.log('Extract status:', status)),
          filter(status => status === 'true' || status === 'done'),
          take(1),
          timeout(30 * 1000),
        )
        .toPromise();

      if (this.settings.isDeveloper) {
        const alert = await this.alertCtrl.show({
          title: 'New update available',
          message: 'There is a new update available',
          buttons: [
            {
              text: 'Install',
              role: 'install',
            },
            {
              text: 'Postpone',
              role: 'cancel',
            },
          ],
        });

        return new Promise(resolve => {
          alert.onDidDismiss((_, role) => {
            if (role === 'install') {
              this.pro.deploy().redirect();
              resolve(true);
            } else {
              resolve(false);
            }
          });
        });
      }
      return false;
    } finally {
      this.checking = false;
    }
  }
开发者ID:ifiske,项目名称:iFiske,代码行数:88,代码来源:deploy.ts


示例13: higherOrder

export function timeout<T>(this: Observable<T>,
                           due: number | Date,
                           scheduler: SchedulerLike = asyncScheduler): Observable<T> {
  return higherOrder(due, scheduler)(this) as Observable<T>;
}
开发者ID:DallanQ,项目名称:rxjs,代码行数:5,代码来源:timeout.ts


示例14: of

 observable1 = constructorZone1.run(() => {
   return of(1).pipe(timeout(10));
 });
开发者ID:angular,项目名称:zone.js,代码行数:3,代码来源:rxjs.Observable.timeout.spec.ts


示例15: shutdownEpic

  shutdownEpic(timeoutMs: number = 2000) {
    const request: JupyterMessage<"shutdown_request", any> = shutdownRequest({
      restart: false
    });

    // Try to make a shutdown request
    // If we don't get a response within X time, force a shutdown
    // Either way do the same cleanup
    const shutDownHandling = this.channels.pipe(
      /* Get the first response to our message request. */
      childOf(request),
      ofMessageType("shutdown_reply"),
      first(),
      // If we got a reply, great! :)
      map((msg: { content: { restart: boolean } }) => {
        return {
          status: "shutting down",
          content: msg.content
        };
      }),
      /**
       * If we don't get a response within timeoutMs, then throw an error.
       */
      timeout(timeoutMs),
      catchError(err => of({ error: err, status: "error" })),
      /**
       * Even if we don't receive a shutdown_reply from the kernel to our
       * shutdown_request, we will go forward with cleaning up the RxJS
       * subject and killing the kernel process.
       */
      mergeMap(
        async (
          event:
            | { status: string; error: Error }
            | {
                status: string;
                content: { restart: boolean };
              }
        ) => {
          // End all communication on the channels
          this.channels.complete();
          await this.shutdownProcess();

          const finalResponse: { error?: Error; status: string } = {
            status: "shutdown"
          };
          if (event.status === "error") {
            finalResponse.error = (event as {
              error: Error;
              status: string;
            }).error;
            finalResponse.status = "error";
          }

          return of(finalResponse);
        }
      ),
      catchError(err =>
        // Catch all, in case there were other errors here
        of({ error: err, status: "error" })
      )
    );

    // On subscription, send the message
    return Observable.create((observer: Observer<any>) => {
      const subscription = shutDownHandling.subscribe(observer);
      this.channels.next(request);
      return subscription;
    });
  }
开发者ID:nteract,项目名称:nteract,代码行数:70,代码来源:kernel.ts


示例16: map

 map(() =>
   buildOutput$.pipe(
     timeout(handlerDelay),
     catchError(() => Rx.of('timeout'))
   )
开发者ID:cjcenizal,项目名称:kibana,代码行数:5,代码来源:watch.ts


示例17: concatMap

    concatMap((action: actions.KillKernelAction) => {
      const kernelRef = action.payload.kernelRef;
      if (!kernelRef) {
        console.warn("tried to kill a kernel without a kernelRef");
        return empty();
      }

      const kernel = selectors.kernel(state$.value, { kernelRef });

      if (!kernel) {
        // tslint:disable-next-line:no-console
        console.warn("tried to kill a kernel that doesn't exist");
        return empty();
      }

      // Ignore the action if the specified kernel is not ZMQ.
      if (kernel.type !== "zeromq") {
        return empty();
      }

      const request = shutdownRequest({ restart: false });

      // Try to make a shutdown request
      // If we don't get a response within X time, force a shutdown
      // Either way do the same cleanup
      const shutDownHandling = kernel.channels.pipe(
        childOf(request),
        ofMessageType("shutdown_reply"),
        first(),
        // If we got a reply, great! :)
        map((msg: { content: { restart: boolean } }) =>
          actions.shutdownReplySucceeded({ content: msg.content, kernelRef })
        ),
        // If we don't get a response within 2s, assume failure :(
        timeout(1000 * 2),
        catchError(err =>
          of(actions.shutdownReplyTimedOut({ error: err, kernelRef }))
        ),
        mergeMap(resultingAction => {
          // End all communication on the channels
          kernel.channels.complete();

          if (kernel.spawn) {
            killSpawn(kernel.spawn);
          }

          return merge(
            // Pass on our intermediate action (whether or not kernel ACK'd shutdown request promptly)
            of(resultingAction),
            // Indicate overall success (channels cleaned up)
            of(
              actions.killKernelSuccessful({
                kernelRef
              })
            ),
            // Inform about the state
            of(
              actions.setExecutionState({
                kernelStatus: "shutting down",
                kernelRef
              })
            )
          );
        }),
        catchError(err =>
          // Catch all, in case there were other errors here
          of(actions.killKernelFailed({ error: err, kernelRef }))
        )
      );

      // On subscription, send the message
      return new Observable(observer => {
        const subscription = shutDownHandling.subscribe(observer);
        kernel.channels.next(request);
        return subscription;
      });
    })
开发者ID:nteract,项目名称:nteract,代码行数:77,代码来源:zeromq-kernels.ts


示例18: intercept

 intercept(
   context: ExecutionContext,
   call$: Observable<any>,
 ): Observable<any> {
   return call$.pipe(timeout(5000));
 }
开发者ID:SARAVANA1501,项目名称:nest,代码行数:6,代码来源:timeout.interceptor.ts



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
TypeScript operators.timeoutWith函数代码示例发布时间:2022-05-25
下一篇:
TypeScript operators.throwIfEmpty函数代码示例发布时间: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