【问题标题】:How to await two requests with Promise.all then invoke other functions in callback?如何使用 Promise.all 等待两个请求,然后在回调中调用其他函数?
【发布时间】:2020-04-09 01:48:06
【问题描述】:

我正在尝试等待两个请求,我从 firebase DB 获取数据并设置为一种状态,

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

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

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

但它没有按预期工作,我可以在控制台中看到 updateData() 在“之前调用” 代码在这里

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

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

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

【问题讨论】:

  • database() .ref( `Providers/CategoriesOrders/${this.state.serviceName[0] || this.state.serviceStorage[0]}`, ) .on('value', this.ordersCallbackOne) 是否返回承诺?
  • @ZHANGLuyao 我认为是的..

标签: javascript reactjs firebase react-native firebase-realtime-database


【解决方案1】:

on('value') 不返回承诺,也不会在这里工作。它仅用于将侦听器附加到查询,并且将无限期地接收结果,直到调用 off()

相反,您应该使用once('value'),它执行一次查询并在完成时返回一个promise。

【讨论】:

  • 呃,我认为 on('value') 像一次一样工作,我重写了它,但 combined 值没有像以前那样记录任何东西!
猜你喜欢
  • 2021-08-14
  • 1970-01-01
  • 2014-05-06
  • 2020-11-19
  • 2021-06-03
  • 2016-10-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多