如何在NodeJs框架Adonisjs中将异步数据从Controller传递到View

时间:2018-05-12 20:09:36

标签: node.js firebase model-view-controller

我是nodejs的新手,并且正在使用名为adonisjs的firebase和nodejs框架。我想问一下如何将数据从控制器传递到视图?这是异步的,因为你知道firebase是异步的。

const firebase = use('App/Controllers/Http/FirebaseController')

class CityController {
  index({view}){
    var db = new firebase().admin().firestore();
    var citiesRef = db.collection('city');
    var data = []
    var allCities = citiesRef.get()
          .then(snapshot => {
            snapshot.forEach(doc => {
              data.push({
                title : doc.id,
                data : doc.data()
              })
            });
            // send data from here?  how?
          })
    return view.render('cities', {data : data}); // data is being sent as empty due to async
  }
}

module.exports = CityController

2 个答案:

答案 0 :(得分:0)

您可以使用AJAX这样操作:

$ajax.({
 url:Your URl Code Here //http://0.0.0.0:333/api/.../+ ID +/...,
 type:"POST",
 status:....,
 compelete:function(result,status...){
    //do what you want in this function      
     }
})

答案 1 :(得分:0)

const firebase = use('App/Controllers/Http/FirebaseController')

class CityController {
  async index({view}){
    var db = new firebase().admin().firestore();
    var citiesRef = db.collection('city');
    var data = []
    await citiesRef.get()
          .then(snapshot => {
            snapshot.forEach(doc => {
              data.push({
                title : doc.id,
                data : doc.data()
              })
            });
            // send data from here?  how?
          })
    return view.render('cities', {data : data}); // data is being sent as empty due to async
  }
}

module.exports = CityController