當前位置: 首頁>>代碼示例>>TypeScript>>正文


TypeScript operators.timeout函數代碼示例

本文整理匯總了TypeScript中rxjs/operators.timeout函數的典型用法代碼示例。如果您正苦於以下問題:TypeScript timeout函數的具體用法?TypeScript timeout怎麽用?TypeScript timeout使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了timeout函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的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


注:本文中的rxjs/operators.timeout函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。