RxJS 等待前一次执行完成 [英] RxJS wait for previous execution to finish

查看:66
本文介绍了RxJS 等待前一次执行完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,所以我是 RxJs 的新手,我无法弄清楚一些事情.我需要实现图像处理,其中用户一次添加多个图像,对于每个图像,除其他外,必须执行以下操作:

Ok, so I'm new to RxJs and I can't figure out some thing. I need to implement image processing in which the user adds multiple images at a time and for each image, among others, following actions must occur:

  1. 在网络工作者中生成图像缩略图
  2. 上传图片和缩略图到服务器

但我不希望一次生成所有缩略图,我希望它们按顺序生成.这是我尝试过的:https://codesandbox.io/s/funny-mountain-tm0jj?expanddevtools=1&fontsize=14

But I don't want all thumbnails to be generated at once, I'd like them to generate sequentially. Here's what I tried: https://codesandbox.io/s/funny-mountain-tm0jj?expanddevtools=1&fontsize=14

我也会在这里粘贴代码:

I'll also paste the code here:

import { of } from "rxjs";
import { map } from "rxjs/operators";

const imageObservable = of(1, 2, 3, 4, 5);

function generateThumbnail(image) {
  console.log(`Generating thumbnail ${image}`);
  return new Promise(resolve => {
    setTimeout(() => {
      console.log(`Finished generating thumbnail ${image}`);
      resolve({
        image,
        thumbnail: `This is a thumbnail of image ${image}`
      });
    }, 1500);
  });
}

async function upload(imagePromise) {
  const image = await imagePromise;
  console.log("Uploading", image);
  return new Promise(resolve => {
    setTimeout(() => {
      console.log("Finished uploading", image);
      resolve();
    }, 1500);
  });
}

imageObservable.pipe(map(generateThumbnail)).subscribe(upload);

我希望 RxJS 等待前一个 generateThumbnail 以执行当前调用(这就是它返回一个 promise 对象的原因)并等待前一个 upload执行当前的(所以 upload 也返回承诺).我不知道如何实现这一目标.有没有 RxJS 忍者愿意帮我解决这个问题?

I'd like RxJS to wait for previous generateThumbnail in order to perform current call (that's why it returns a promise object) and also wait for previous upload in order to perform the current one (so upload is also returning promise). I have no idea how to achieve that. Any RxJS ninja would like to help me with that?

推荐答案

您只想按顺序生成缩略图还是生成第二个缩略图也需要等待第一个缩略图上传完成?

Do you only want generating thumbnails to be sequential or does generation of a second thumbnail need to wait for upload of the first one to finish as well?

如果你不想等待上传,你只需要连接它们:

If you don't want to wait for upload, you just need to concat them:

import { of, from, } from 'rxjs';
import { concatMap } from 'rxjs/operators';

const imageObservable = of(1, 2, 3, 4, 5);

function generateThumbnail(image) {
    console.log(`Generating thumbnail ${image}`);
    return new Promise(resolve => {
        setTimeout(() => {
            console.log(`Finished generating thumbnail ${image}`);
            resolve({
                image,
                thumbnail: `This is a thumbnail of image ${image}`
            });
        }, 1500);
    });
}

async function upload(imagePromise) {
    const image = await imagePromise;
    console.log('Uploading', image);
    return new Promise(resolve => {
        setTimeout(() => {
            console.log('Finished uploading', image);
            resolve();
        }, 1500);
    });
}

// imageObservable.pipe(map(generateThumbnail)).subscribe(upload);

imageObservable.pipe(concatMap(image => from(generateThumbnail(image)))).subscribe();

concatMap 做你想做的,我只是做了一个 Observable 从你的 Promisefrom 创建操作符中分离出来,我认为这是不需要的.但是当你使用 RxJs 时,使用 Observables 而不是 Promises 通常更容易.

concatMap does what you want, and I just made an Observable out of your Promise with from creational operator, which I don't think is needed. But it's usually easier to work with Observables instead of Promises when you use RxJs.

function generateThumbnail(image): Observable<any> {
    console.log(`Generating thumbnail ${image}`);
    return from(
        new Promise(resolve => {
            setTimeout(() => {
                console.log(`Finished generating thumbnail ${image}`);
                resolve({
                    image,
                    thumbnail: `This is a thumbnail of image ${image}`
                });
            }, 1500);
        })
    );
}

你可以试试这个吗?

imageObservable
    .pipe(
        concatMap(image => generateThumbnail(image)),
        concatMap(image => upload(image))
    )
    .subscribe();

这篇关于RxJS 等待前一次执行完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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