node.js - Rxjava2如何简洁地将结果从前一个节点返回到链中的下一个节点
问题描述
我在android中使用rxjava2,有时会遇到这样的问题:
Observable.fromArray(
// maybe a list about photo url in SDCard
)
.flatMap(
// make list to single and upload to server,
// use retrofit observable<uploadResponse>
)
.map(uploadResponse -> {
// *Problem of point
})
.map(
// in this map I want to get this single photo url in SDCard
// and some info from uploadResponse,how to do in
// *Problem of point of previous map?
);
这段代码忽略了一些线程切换和其他不重要的步骤。这个问题也让我对 nodejs 的 Promise 感到困惑,如何将一些值传递给链的每一步?我在 firebase 上使用 nodejs 的 version6,它不支持等待。
解决方案
至于问题的 JavaScript 部分,可以通过以下方式方便地解决async..await
:
(async () => {
const foo = await fooPromise;
const bar = await getBarPromise(foo);
const baz = await getBazPromise(bar);
})()
.catch(console.error);
我在firebase上使用nodejs的版本6,它不支持等待。
自从 Node 4 中出现生成器以来,背后的模式async..await
就被广泛使用。同样的事情可以用co
最著名的实现来实现:
const co = require('co');
co(function * () {
const foo = yield fooPromise;
const bar = yield getBarPromise(foo);
const baz = yield getBazPromise(bar);
})
.catch(console.error);
由于async
function 是 promise 的语法糖,因此async
function 所做的一切都可以仅用 promise 重写。
鉴于以后可能需要一个值(foo
):
fooPromise
.then(foo => getBarPromise(foo))
.then(bar => getBazPromise(bar))
.then(baz => {
// foo and baz are needed here
});
它应该与其他结果一起通过链:
fooPromise
.then(foo => {
return getBarPromise(foo).then(bar => ({ foo, bar }));
})
.then(({ foo, bar }) => {
return getBazPromise(bar).then(baz => ({ foo, baz }));
})
.then(({ foo, baz }) => {
// foo and baz are destructured from the result
});
或者应该嵌套承诺以便foo
在当前函数范围内可用:
fooPromise
.then(foo => {
return getBarPromise(foo)
.then(bar => getBazPromise(bar))
.then(baz => {
// foo and baz are available here
})
});
相同的配方适用于其他 API 和语言。例如,RxJS:
fooObservable
.flatMap(foo => Observable.zip(
Observable.of(foo),
getBarObservable(foo)
))
.map(([foo, bar]) => {
// foo and bar are destructured from the result
})
推荐阅读
- arrays - 在 postgresql 中更新多维数组
- python - 检索张量中 1 的位置或将张量拆分为 1
- html - 如何使用 HTML 将 CSS 中的 DIV 元素居中?
- python - Graph 执行中不允许使用 `tf.Tensor` 作为 Python `bool`。使用 Eager 执行或用 @tf.function 修饰这个函数
- django - DRF 所需的搜索过滤器
- html - 图像的最大宽度在 IE 11 的 flexbox 中不起作用,但适用于谷歌浏览器
- javascript - 我无法在 if 语句中分配变量
- r - 将 ggplot 中的 x 轴设置为在最后一个日期数据结束时可用于
- django - 'list' 对象没有属性 'json'
- php - Laravel 无需事先排序即可获取最新行