如何在 Cycle.js 中按顺序请求数据? [英] How to request data sequentially in Cycle.js?

查看:50
本文介绍了如何在 Cycle.js 中按顺序请求数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是响应式编程的新手,并在玩cycle.js,试图从本教程中实现谁可以关注框

I’m new to reactive programming and toying around with cycle.js, trying to implement who to follow box from this tutorial. But I understood that for proper implementation (and learning purposes) I don’t have one piece of data: full user name. I can get it by sequentially getting users and then full user data from server. In imperative style I would do something like this:

fetch(`https://api.github.com/users`)
  .then(data => data.json())
  .then(users => fetch(users[0].url))
  .then(data => data.json())
  .then(/* ... work with data ... */)

但是我如何在循环中做到这一点?我正在使用 fetch 驱动程序并尝试这样的事情:

But how do I do it in cycle? I’m using fetch driver and trying something like this:

function main({ DOM, HTTP }) {
  const users = `https://api.github.com/users`;

  const refresh$ = DOM.select(`.refresh`).events(`click`)

  const response$ = getJSON({ key: `users` }, HTTP)

  const userUrl$ = response$
    .map(users => ({
      url: R.prop(`url`, R.head(users)),
      key: `user`,
    }))
    .startWith(null)

  const request$ = refresh$
    .startWith(`initial`)
    .map(_ => ({
      url: `${users}?since=${random(500)}`,
      key: `users`,
    }))
    .merge(userUrl$)

  const dom$ = ...

  return {
    DOM: dom$,
    HTTP: request$,
  };
}

getJSON 在哪里

function getJSON(by, requests$) {
  const type = capitalize(firstKey(by));

  return requests$
    [`by${type}`](firstVal(by))
    .mergeAll()
    .flatMap(res => res.json());

而且我总是收到一些神秘的(对我来说)错误,例如:TypeError: Already read.这是什么意思,我该如何正确处理?

And I’m always getting some cryptic (for me) error like: TypeError: Already read. What does it mean and how do I handle it properly?

推荐答案

你们已经很接近了.您只需要删除 startWith(null) 作为请求,并获取第二个响应(您错过了那个响应的 getJSON).

You were quite close. You just need to remove startWith(null) as a request, and grabbing the second response (you were missing the getJSON for that one).

function main({ DOM, HTTP }) {
  const usersAPIPath = `https://api.github.com/users`;

  const refresh$ = DOM.select(`.refresh`).events(`click`);

  const userResponse$ = getJSON({ key: `user` }, HTTP);
  const listResponse$ = getJSON({ key: `users` }, HTTP);

  const userRequest$ = listResponse$
    .map(users => ({
      url: R.prop(`url`, R.head(users)),
      key: `user`,
    }));

  const listRequest$ = refresh$
    .startWith(`initial`)
    .map(_ => ({
      url: `${usersAPIPath}?since=${Math.round(Math.random()*500)}`,
      key: `users`,
    }));

  const dom$ = userResponse$.map(res => h('div', JSON.stringify(res)));

  return {
    DOM: dom$,
    HTTP: listRequest$.merge(userRequest$),
  };
}

这篇关于如何在 Cycle.js 中按顺序请求数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆