sách gpt4 ai đã đi

Rxjava2 cách trả về kết quả một cách ngắn gọn từ Node trước đó đến Node tiếp theo trong chuỗi

In lại 作者:太空宇宙 更新时间:2023-11-04 00:07:16 34 4
mua khóa gpt4 Nike

我在android中使用rxjava2,有时会遇到这样的问题:

Observable.fromArray(
// maybe a list about photo url in SDCard
)
.flatMap(
// make list to single and upload to server,
// use retrofit observable
)
.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的版本6,它不支持await。

1 Câu trả lời

对于问题的JavaScript部分,可以使用async..await方便地解决:

(async () => {
const foo = await fooPromise;
const bar = await getBarPromise(foo);
const baz = await getBazPromise(bar);
})()
.catch(console.error);

I use nodejs's version6 on firebase,it not support await.

自从 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);

由于 không đồng bộ 函数是 Promise 的语法糖,因此 không đồng bộ 函数所做的一切都可以单独用 Promise 重写。

假设有一个稍后可能需要的值(đồ ăn):

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
});

或者 Promise 应该嵌套,以便 đồ ăn 在当前函数作用域内可用:

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
})

关于node.js - Rxjava2如何简洁地将结果从前一个 Node 返回到链中的下一个 Node ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51687404/

34 4 0
太空宇宙
Hồ sơ cá nhân

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá Didi Taxi miễn phí
Mã giảm giá Didi Taxi
Giấy chứng nhận ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com