快速获取请求承诺

时间:2019-10-09 12:09:29

标签: express promise

我正在使用带有两个find查询的get请求,但是执行异步运行时,我需要依次执行第一个查询,因为我需要使用promise或任何其他方式来解决这个问题?我正在努力做什么,要一步一步地执行此代码。请让我知道如何使用Promise?我是Express的新手

app.get("/cryptonews/:page", function (req, res) {
        let page=req.params.page;
        const perpage=10;
        var page_name;
        // console.log("lengthtotal",news.length);
        var  length;
         news.find().sort({newsDate: -1}).exec(function (err, news) {
           console.log("1st");
            if (err) {
                console.log(err);
            }
            length=news.length;
            console.log("length2",length);

         });

        news.find()
      .sort({newsDate: -1}).skip((perpage * page) - perpage)
      .limit(perpage).exec(function(err, news){
        console.log("2nd");
           if (err) {
                console.log(err);
            }
            const numOfProducts = length;
console.log("length",numOfProducts)
// news.count({'_id'});
 if(req.session.user != null){

if(req.session.user.address){
            var self =this;
            const smartContrat = self.web3.eth.contract(self.abi).at(contractAddress);
            const balance = smartContrat.balanceOf(req.session.user.address) / 1e18;
            // console.log(balance,"balance")


res.render('cryptonews', {
     sess: req.session,
   news: news, 
    imageurl,
    balance:balance,
   currentPage: page, 
   pages: Math.ceil( numOfProducts  / perpage), 

   numOfResults: numOfProducts ,
    page_name:'news',
  });

}
 else{
         res.render('cryptonews', {
               sess: req.session,
                news: news,
                imageurl,
                 currentPage: page, 
   pages: Math.ceil(numOfProducts / perpage), 

   numOfResults: numOfProducts,
     page_name:'news',


            });
            //  console.log("news",news);
            //  console.log("news",news);
  // console.log("news length",pages);
  // console.log("currentpage:", currentPage)
     }
}

else{
  res.render('cryptonews', {
               sess: req.session,
                news: news,
                imageurl,
                 currentPage: page, 
   pages: Math.ceil(numOfProducts / perpage), 
   numOfResults: numOfProducts,
   page_name:'news',




})

}
      })

1 个答案:

答案 0 :(得分:0)

当您不向exec函数传递任何回调时,您可以在此处使用promise。

一旦获得承诺,您就可以附加然后捕获回调,也可以直接使用await关键字来获取承诺的结果。

请参考下面的代码

  

使用then catch

app.get('/cryptonews/:page', function (req, res) {
  const page = req.params.page
  const perpage = 10
  var page_name
  // console.log("lengthtotal",news.length);
  var length
  news.find().sort({ newsDate: -1 }).exec().then(function () {
    console.log('1st')
    length = news.length
    console.log('length2', length)

    news.find()
      .sort({ newsDate: -1 })
      .skip((perpage * page) - perpage)
      .limit(perpage).exec().then(function () {
        console.log('2nd')

        const numOfProducts = length
        console.log('length', numOfProducts)
        // news.count({'_id'});
        if (req.session.user != null) {
          if (req.session.user.address) {
            var self = this
            const smartContrat = self.web3.eth.contract(self.abi).at(contractAddress)
            const balance = smartContrat.balanceOf(req.session.user.address) / 1e18
            // console.log(balance,"balance")

            res.render('cryptonews', {
              sess: req.session,
              news: news,
              imageurl,
              balance: balance,
              currentPage: page,
              pages: Math.ceil(numOfProducts / perpage),
              numOfResults: numOfProducts,
              page_name: 'news'
            })
          } else {
            res.render('cryptonews', {
              sess: req.session,
              news: news,
              imageurl,
              currentPage: page,
              pages: Math.ceil(numOfProducts / perpage),
              numOfResults: numOfProducts,
              page_name: 'news'
            })
            // console.log("news", news);
            //  console.log("news",news);
            // console.log("news length",pages);
            // console.log("currentpage:", currentPage)
          }
        } else {
          res.render('cryptonews', {
            sess: req.session,
            news: news,
            imageurl,
            currentPage: page,
            pages: Math.ceil(numOfProducts / perpage),
            numOfResults: numOfProducts,
            page_name: 'news'
          })
        }
      }).catch(console.log)
  }).catch(console.log)
})
  

使用async await

app.get('/cryptonews/:page', async function (req, res) {
  const page = req.params.page
  const perpage = 10
  var page_name
  // console.log("lengthtotal",news.length);

  try {
    var firstQueryResult = await news.find().sort({ newsDate: -1 }).exec()
    console.log('length2', length)

    var secondQueryResult = await news.find()
      .sort({ newsDate: -1 })
      .skip((perpage * page) - perpage)
      .limit(perpage).exec()
  } catch (err) {
    console.log(err)
    throw err
  }

  const numOfProducts = firstQueryResult.length
  console.log('length', numOfProducts)
  // news.count({'_id'});
  if (req.session.user != null) {
    if (req.session.user.address) {
      var self = this
      const smartContrat = self.web3.eth.contract(self.abi).at(contractAddress)
      const balance = smartContrat.balanceOf(req.session.user.address) / 1e18
      // console.log(balance,"balance")

      res.render('cryptonews', {
        sess: req.session,
        news: secondQueryResult,
        imageurl,
        balance: balance,
        currentPage: page,
        pages: Math.ceil(numOfProducts / perpage),
        numOfResults: numOfProducts,
        page_name: 'news'
      })
    } else {
      res.render('cryptonews', {
        sess: req.session,
        news: secondQueryResult,
        imageurl,
        currentPage: page,
        pages: Math.ceil(numOfProducts / perpage),
        numOfResults: numOfProducts,
        page_name: 'news'
      })
      // console.log("news", news);
      //  console.log("news",news);
      // console.log("news length",pages);
      // console.log("currentpage:", currentPage)
    }
  } else {
    res.render('cryptonews', {
      sess: req.session,
      news: secondQueryResult,
      imageurl,
      currentPage: page,
      pages: Math.ceil(numOfProducts / perpage),
      numOfResults: numOfProducts,
      page_name: 'news'
    })
  }
})