js 回调地狱的另类解决方案尝试

例如 经过学生获取学生所在学校信息,须要先查询学生所在班级,再经过班级查询所在学校信息。js代码相似写法以下:javascript

function getStudentSchool(id) {
    ajax.get("/Test/GetStudent", { "studentId": id }, function (student) {
        if (student != null && student.ClassId != null) {
            ajax.get("/Test/GetClass", { "classId": student.ClassId }, function (studentClass) {
                if (studentClass != null && studentClass.SchoolId != null) {
                    ajax.get("/Test/GetSchool", { "schoolId": studentClass.SchoolId }, function (school) {
                        if (school != null) {
                            console.log(school);
                        }
                    });
                }
            });
        }
    });
}
 
//调用入口方法
window.οnlοad= function(){
	getStudentSchool(1);
};

  写了个类经过设置相关业务信号量来绑定触发的方法,当信号变量改变时就会自动调用相应的方法,改进方法以下:html

function AsynFlag() { if (typeof this.setFlag != "function") { AsynFlag.prototype.setFlag = function (obj, name, fun) { if (obj.hasOwnProperty(name)) { obj[name + "_fun"] = fun; return; } obj[name] = 0; obj[name + "_"] = 0; Object.defineProperty(obj, name, { get: function () { return obj[name + "_"]; }, set: function (value) { if (value != obj[name + "_"]) { obj[name + "_"] = value; } else { return; } if (obj[name + "_fun"] == null) { obj[name + "_fun"] = fun; } obj[name + "_fun"](); } }); }; } } var param = { "studentId": 0, "classId": 0, "schoolId": 0 }; var s = new AsynFlag(); var flag = {}; function getStudent() { ajax.get("/Test/GetStudent", { "studentId": param.studentId }, function (student) { if (student != null && student.ClassId != null) { param.classId = student.ClassId; s.setFlag(flag, "canGetClass", getClass); flag.canGetClass = true; } }); } function getClass() { ajax.get("/Test/GetClass", { "classId": param.ClassId }, function (studentClass) { if (studentClass != null && studentClass.SchoolId != null) { param.SchoolId = studentClass.SchoolId; s.setFlag(flag, "canGetSchool", getSchool); flag.canGetSchool = true; } }); } function getSchool() { ajax.get("/Test/GetSchool", { "schoolId": param.SchoolId }, function (school) { if (school != null) { console.log(school); } }); } //调用入口方法
window.onload= function(){ param.studentId =1; getStudent(); };

flag 是个信号量设置对象,s.setFlag(flag, "canGetClass", getClass); 设置flag拥有canGetClass属性,而且该属性绑定函数getClass,  当第一个ajax得到数据后设置信号并改变信号量触发绑定的getClass函数,flag对象中会自动建立canGetClass,java

canGetClass_, 两个属性和一个canGetClass_fun方法来实现当canGetClass改变时调用canGetClass_fun=getClass。git

以上代码实际测试可行。github

代码已上传github https://github.com/SaFaJim/AsynFlag
————————————————
版权声明:本文为CSDN博主「皮皮虾大侠」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处连接及本声明。
原文连接:https://blog.csdn.net/Asa_Jim/article/details/86648199ajax

原文出处:https://www.cnblogs.com/DeepinCoding/p/11995287.html函数

相关文章
相关标签/搜索