Node.js-在返回响应之前未运行DB Promise

时间:2018-11-23 15:10:36

标签: javascript node.js asynchronous

我的节点服务器上有此请求处理程序。它有三个MongoDB查询,我希望在发送响应之前返回所有结果。

export default class Config extends Component {
  static navigationOptions = { 
    header: null,
    drawerIcon: ({ tintColor }) => ( <Icon name='settings' style={{color:tintColor ,fontSize:24}} />)
    }
  SignOut = async() => {
    AsyncStorage.clear()
    this.props.navigation.navigate('AuthLoading')
  }

    render() {
      return (
          <Container>
          <Header>
            <Left style={{flex:1}}>
            <Icon name="menu" color='black' size={24} onPress={() => this.props.navigation.openDrawer()}/>
            </Left>
            <Body style={{flex: 1,justifyContent: 'center'}}>
              <Title>Configurações</Title>
            </Body>
            <Right style={{flex:1}}/>
          </Header>
          <View style={{flex :1, alignItems:'center', justifyContent:'center'}}>                    
                    <Text>Configurações</Text> 
                    </View> 
        </Container>
      );
  }
}

但是运行此命令会返回

api.get('/getStats/:productID', (req,res)=>{
  let data = {};
  let dailySales = [];
  let avgProduct = "";
  let customers = [];

  Sales.find({productID: productID}).then(
    sales => {
      dailySales = sales;
    }
  );

  Products.find({}).then(
    products => {
      // Calculate Avg product here
      avgProduct = result;
    }
  );

  Customers.find({}).then(
    customers => {
      customers = customers;
    }
  );

  data = {
    dailySales,
    avgProduct,
    customers
  };

  res.json(data);
});

即运行数据之前,Mongo响应将返回。请如何解决。谢谢

3 个答案:

答案 0 :(得分:5)

等待所有诺言解决,然后再发送实际回复

const sales = Sales.find({productID: productID});
const allProducts = Products.find({});
const allCustomers = Customers.find({});

Promise.all([sales, allProducts, allCustomers])
 .then(data => res.json(data));  

答案 1 :(得分:1)

您可以尝试使用Promise.all,在其中可以将MongoDB查询作为参数传递给它,当所有查询将结果返回到数组中时,promise都将得到解决

答案 2 :(得分:0)

  

尝试将内置util.promisify函数与   异步等待以正确获取数据!

const promisify = require('utils').promisify;

const salesFindOnePromise = promisify(Sales.find);
const productsFindAllPromise = promisify(Products.find);
const customersFindAllPromise = promisify(Customers.find);

findDailySalesByIdAsync = async (productID) => {

    try {
        return await salesFindOnePromise({ productID: productID });
    } catch(err) {
        throw new Error('Could not fetch the appropriate sales with productID');
    }

}

findProductsAsync = async () => {

    try {
        return await productsFindAllPromise({});
    } catch (err) {
        throw new Error('Could not fetch sales!');
    }
}

findCustomersAsync = async () => {

    try {
        return await customersFindAllPromise({});
    } catch (err) {
        throw new Error('Could not fetch customers!');
    }
}


api.get('/getStats/:productID', async (req,res)=>{

try {
  const dailySales = await findDailySalesByIdAsync(productID);
  const avgProduct = await findProductsAsync();
  const customers = await findCustomersAsync();

    const data = {
        dailySales,
        avgProduct,
        customers
    };

    return res.status(200).send(data);

  } catch(err) {
    console.err(`Failed because: {err}`);
    throw new Error('Could not fetch data because of some error!');
  }

});