Rxjs 拼接请求比较优雅的方式

想用rxjs 解决请求拼接发送的场景: 下一个请求需要上一个请求的结果。

最原始的方式,或者使用async,效果类似。

fetch('http://api.manster.me/p1').then((p1) => p1.json())
  .then((res) => {
    fetch('http://api.manster.me/' + res.next)
      .then((res) => res.json()).then((res) => {
        fetch('http://api.manster.me/' + res.next)
          .then((res) => res.json()).then((res) => {
            console.log(res);
          })
      })
  })

用rxjs(v6)改了一般,总感觉不太优雅

const s1 = from(fetch('http://api.manster.me/p1').then(res => res.json()));
const p =
    s1.pipe(
        mergeMap((res) => from(fetch('http://api.manster.me/' + res.next).then(res => res.json()))),
        mergeMap((res) => from(fetch('http://api.manster.me/' + res.next).then(res => res.json())))
    )

p.subscribe(console.log)

怎么把 then(res => res.json()) 干掉?
请赐教一个好的写法。感谢

阅读 2.3k
1 个回答

把一些相同的逻辑封装起来

const get = url => fetch(url).then(res => res.json())

/**
 * @param {string} api 需要请求的 api
 */
const getApi = api => get(`http://api.manster.me/${api}`)

from(getApi(`p1`))
  .pipe(
    flatMap(res => getApi(res.next)),
    flatMap(res => getApi(res.next)),
  )
  .subscribe(console.log)

如果下一个请求的逻辑一样的话,还可以把 next 封装起来

const getNext = res => getApi(res.next)

from(getApi(`p1`))
  .pipe(
    flatMap(getNext),
    flatMap(getNext),
  )
  .subscribe(console.log)
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题