Rxjs 如何按顺序执行 Promise

Rxjs 如何按顺序执行 Promise

相关代码

const { of, from, forkJoin } = require("rxjs");
const { catchError } = require("rxjs/operators");

const the_test1 = new Promise((resolve, reject) => {
  setTimeout(() => {
    reject("fail");
  }, 2000);
});

const the_test2 = new Promise(resolve => {
  setTimeout(() => {
    resolve("success");
  }, 2000);
});

const the_test3 = new Promise(resolve => {
  setTimeout(() => {
    resolve("success");
  }, 2000);
});

const promiseToObservable = promise => {
  return from(promise).pipe(catchError(err => of(err)));
};

const StartTime = new Date().getTime();
forkJoin([
  promiseToObservable(the_test1),
  promiseToObservable(the_test2),
  promiseToObservable(the_test3)
]).subscribe(val => {
  console.log(val);
  console.log(new Date().getTime() - StartTime);
});

在线调试

https://codesandbox.io/s/bold-blackburn-p2nhy

问题描述

希望等待 the_test1 执行完成后再执行 the_test2,the_test2 执行完成后再执行 the_test3。6s 后返回结果而不是并发执行。

你期待的结果是什么?

目前为并发执行,大约 2s 左右返回接口,希望串行,大约 6s 左右返回结果

阅读 5.1k
1 个回答

首先你要明白 new Promise(executor)executor 方法是立即执行的,所以你的问题不在 RxJS 而在你创建几个 the_test 的时候就已经开始跑异步逻辑了。

解决方式有很多种,下面是一个例子

const { of } = require("rxjs");
const { concatMap, reduce, catchError } = require("rxjs/operators");

const the_test1 = () =>
  new Promise((resolve, reject) => {
    setTimeout(() => {
      reject("fail");
    }, 2000);
  });

const the_test2 = () =>
  new Promise(resolve => {
    setTimeout(() => {
      resolve("success");
    }, 2000);
  });


const the_test3 = () =>
  new Promise(resolve => {
    setTimeout(() => {
      resolve("success");
    }, 2000);
  });

console.log('starting...');
const StartTime = new Date().getTime();
of(the_test1, the_test2, the_test3).pipe(
  concatMap(test => test().catch(err => err)),
  reduce((acc, cur) => [...acc, cur], [])
).subscribe(val => {
  console.log(val);
  console.log(new Date().getTime() - StartTime);
});

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题