【问题标题】:Using RX JS to make a pause between functions使用 RX JS 在函数之间进行暂停
【发布时间】:2021-10-06 14:38:18
【问题描述】:

我有一些(大约 10 个左右)对 API 的请求,并且该 API 的限制为每秒 1 个请求。我想使用 RX JS 在每个函数后暂停。我的代码如下所示:

const source = interval(1000);
const getData = async() => { 
    let info = {
        date: new Date(),
        id: initialId,
    };
    if (fetchInitialResponse(initialId) ) { //external function that checks whether entry exists
       info['Names'] = await fetchResponse( getUrl(ADDRESSOTHERNAMES), process.env.OTHERNAMESFOUND);
       info['Address'] = await fetchResponse( getUrl(ADDRESSADDRESS), process.env.ADDRESSFOUND);
       info['Individuals'] = await fetchResponse( getUrl(ADDRESSINDIVIDUALS), process.env.INDIVIDUALSFOUND);
       //and so on with about 10 functions
        mongoConnect(true, info) //external function that writes the recieved info to mongodb 
    }
} 

const subscribe = source.subscribe( () => getData() );

如何在每个 'await fetchResponse' 函数后暂停?

【问题讨论】:

    标签: javascript rxjs


    【解决方案1】:

    这应该将您的调用间隔 1 秒(使用 zip),然后将响应构建到一个信息对象中为您(使用 reduce)

    const initialId = 1234; // Or whatever
    
    const data$ = of({
      date: new Date(),
      id: initialId
    }).pipe(
      filter(({id}) => fetchInitialResponse(id)),
    
      switchMap(info => {
        const apiCalls = [
    
          from(fetchResponse( 
            getUrl(ADDRESSOTHERNAMES), 
            process.env.OTHERNAMESFOUND
          )).pipe(
            map(names => ({...info, names}))
          ),
    
          from(fetchResponse( 
            getUrl(ADDRESSADDRESS), 
            process.env.ADDRESSFOUND
          )).pipe(
            map(address => ({...info, address}))
          ),
    
          from(fetchResponse( 
            getUrl(ADDRESSINDIVIDUALS), 
            process.env.INDIVIDUALSFOUND
          )).pipe(
            map(individuals => ({...info, individuals}))
          ),
    
          //and so on with about 10 functions
        ];
    
        return zip(interval(1000), apiCalls);
      }),
    
      reduce(Object.assign)
    
    ).subscribe(info => mongoConnect(true, info));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-22
      • 2016-12-19
      • 2019-10-18
      • 1970-01-01
      • 1970-01-01
      • 2022-11-30
      • 1970-01-01
      • 2017-02-08
      相关资源
      最近更新 更多