本文介绍了如何使用Promise.all等待两个请求,然后在回调中调用其他函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试等待两个请求,这些请求是我从firebase DB中获取数据并设置为状态的,

I'm trying to wait for two requests I get data from firebase DB and set into a state,

我想要在完成两个请求之后,将结果数据连接到一个数组中,

I want after two requests Done, concatenate result data in one array,

所以我尝试将两个请求推送到一个数组中,然后使用

So I tried to push two requests in an array then use

> Promise.all(promises).then(()=>this.updateData());

,但无法正常工作,我可以在控制台"updateData()"之前看到此处代码

but it does not work as expected, I can see in the console updateData() invoked before "Code here

 fetchOrders = async () => {
         ....
 let promises = [];
    promises.push(
      //  First service orders
      database()
        .ref(
          `Providers/CategoriesOrders/${this.state.serviceName[0] ||
            this.state.serviceStorage[0]}`,
        )
        .on('value', this.ordersCallbackOne),
    );



promises.push(
      // Second service orders
      database()
        .ref(
          `Providers/CategoriesOrders/${this.state.serviceName[1] ||
            this.state.serviceStorage[1]}`,
        )
        .on('value', this.ordersCallbackTwo),
    );

  Promise.all(promises).then(() => this.updateData());
  };



ordersCallbackTwo = snapshot => {
    let orderArr = [];
    snapshot.forEach(childSnapshot => {
      orderArr.push({
        snapshotKey: childSnapshot.key,
        username: childSnapshot.val().username,
      });
    });
    this.setState({orderServiceTwo: orderArr}, () =>
      console.log('2', this.state.orderServiceTwo), // it's log data here
    );
  };

两个请求完成后我要调用的函数.

the function I want to invoke after two requests Done.

  updateData = () => {
    // if (this.rejectedOrders?.length >= 1) {
    //   const orders = this.state.orders.filter(
    //     order => !this.rejectedOrders.some(key => order.snapshotKey === key),
    //   );
    //   this.setState({orders, loading: false});
    //   return;
    // }

    console.log('ordersOne!', this.state.orderServiceOne); // empty!

    const order1IDs = new Set(
      this.state.orderServiceOne.map(({snapshotKey}) => snapshotKey),
    );
    console.log('order1IDs', order1IDs);
    const combined = [
      ...this.state.orderServiceOne,
      ...this.orderServiceTwo?.filter(
        ({snapshotKey}) => !order1IDs.has(snapshotKey),
      ),
    ];
    console.log('combined', combined);
    this.setState({
      orders: combined,
      loading: false,
    });
  };

推荐答案

on('value')不会返回承诺,因此无法在此处使用.它仅用于将侦听器附加到查询,并且会无限期地接收结果,直到调用off().

on('value') doesn't return a promise and won't work here. It's only used to attach a listener to a query, and will receive results indefinitely until call off().

相反,您应该使用一次('值') ,该查询一次执行一次查询,并在查询完成后返回一个Promise.

Instead, you should use once('value'), which executes the query a single time and returns a promise when it completes.

这篇关于如何使用Promise.all等待两个请求,然后在回调中调用其他函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 07:05