search

Home  >  Q&A  >  body text

javascript - How to implement asynchronous loop query nesting

Assume that there is an existing student dictionary array, and the students have names and classroom numbers. First, query the schools that meet the conditions, facilitate the student dictionary array, create a student object and assign the name, school and class, but the class needs to query the location of the classroom first. To confirm, will there be a circular query? How to solve such a problem?

var studentArr = new Array({'name': 'a','room':'101'},{'name': 'b','room':'102'},{'name': 'c','room':'103'},{'name': 'd','room':'104'});
var objects = new Array();
var schoolQuery = new AV.Query(Shcool);
schoolQuery.equalTo('name','**高中');
schoolQuery.find().then(function(schoolReuslts){
    for (var i = 0; i < studentArr.count; i ++){
        var student = studentArr[i];
        var object = new Student();

        object.set('name',student['name']);
        object.set('room',student['room']);
        object.set('school',schoolReuslts[0]);

        var classQuery = new AV.Query(Class);
        classQuery.equalTo('school',schoolReuslts[0]);
        classQuery.equalTo('room',student['room']);
        classQuery.find().then(function(classResults){
                object.set('class',classResults[0]);
                objects.push(object);
            }, function(error){
                console.log(error);
            });
        }
    return AV.Object.saveAll(objects);
}).then(function(objects){
    //全部保存成功    
}
}).catch(function(error) {
    console.log(error);
ringa_leeringa_lee2758 days ago982

reply all(1)I'll reply

  • 怪我咯

    怪我咯2017-07-05 10:38:27

    You can use nesting of asynchronous functions, async/await node.js version >7.10.0

    reply
    0
  • Cancelreply