Promise应用场景

场景举例:分类信息展示

实际开发里,可能有的数据是由多个接口调用获取,那多个接口需要伪嵌套

(1)需求:表单中用户姓名与职业的分类信息展示

  1、初步模板如下

    

     

  2、需求:做一个用户编辑操作,但这里注意职业是从服务端动态差进来的

    

     所以这里需要两张表,即用户表+职业表

    

     

注意:用户表里,存储用户信息时,职业存储实际上是一个id,不是具体的职业名,即多表联表查询,节省空间

    例如,信息存储时职业对应数字为4,则该人员职业为职业信息表中ID为4的职业

    

     如果为job为2,则对应职业信息表里ID为2的职业

  3、接下来设计下接口文档

    同级新建文件data.json用于模拟存储数据,为了解决数据冗余问题,用户信息处的职业保存的时职业表里对应的id

    

    接下来需要查询两个数据接口,获取用户信息和职业,接下来开一个接口,详见文章json-server模拟服务器API .

    再新增几条数据

{
    "users":[
        {
            "id":1,
            "username":"张三",
            "age":22,
            "job":2
        },
        {
            "id":2,
            "username":"李四",
            "age":18,
            "job":4
        },
        {
            "id":3,
            "username":"王五",
            "age":36,
            "job":3
        }
    ],
    "jobs":[
        {
            "id":1,
            "name":"学生"
        },
        {
            "id":2,
            "name":"老师"
        },
        {
            "id":3,
            "name":"保安"
        },
        {
            "id":4,
            "name":"电工"
        }
    ]
}

    例如想获取id为2的用户信息,接口路径如下

    

    将之前封装的ajax方法调用过来,然后进行调用,如下所示

    

     接下来刷新页面,做下测试

    

     此时页面控制台根据接口输出id为2的学生信息,因为默认格式为字符串,需要进行解析成js对象

    

         

  4、模板引擎

    接下来需要将对象内容结合模板引擎art-template(前端客户端模板引擎)渲染到页面,首先下载到当前项目,然后引入

    

     

    编写渲染模板,将form表单内容编写至模板里

    

     然后编写渲染语法

    

     模板变量

    

     然后进行渲染

    

     此时刷新页面,结果如下(id为2的员工信息)

    

(2)职业数据

  接下来操作职业数据

  

   然后需要判断当前人员职业,将该职业设为默认选中状态

  

  此时便完成了接口调用渲染

  

此时看到的数据,便是通过两个接口结合获取的。
假设需要用到3个、4个更多接口,代码嵌套太深,这是callbak方式的解决方式
接下来可以使用Promise方法解决
注意:【jQuery】的ajax已经支持promise的api方式

  总结代码如下

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Promise应用场景举例--信息分类展示</title>
</head>
<body>
    <form id="user_form">
        
    </form>
    <script type="text/javascript" src="node_modules/art-template/lib/template-web.js"></script>
    <script type="text/template" id="tpl">
        <div>
            姓名:
            <input type="text" name="username" value="{{user.username}}">
        </div>
        <div>
            年龄:
            <input type="number" name="userage" value="{{user.age}}">
        </div>
        <div for="job">
            职业
            <select>
                {{each jobs}}
                    {{if $value.id === user.job}}
                        <option id="{{$value.id}}" selected>{{$value.name}}</option>
                        {{else}}
                        <option id="{{$value.id}}">{{$value.name}}</option>
                    {{/if}}
                {{/each}}
            </select>
        </div>
    </script>
    <script type="text/javascript">
        get('http://localhost:3000/users/2',function(usersData){
            get('http://localhost:3000/jobs',function(jobsData){
                var htmlStr = template('tpl',{
                    user:JSON.parse(usersData),
                    jobs:JSON.parse(jobsData)
                })
                document.querySelector('#user_form').innerHTML = htmlStr
            })
            
        })
        /*自定义封装ajax*/
        function get(url,callback){
            var xhr;
            if (window.XMLHttpRequest) {
                xhr = new XMLHttpRequest()
            } else {
                xhr = new ActiveXObject("Microsoft.XMLHTTP")
            }
            xhr.open('get',url, true)
            xhr.send()
            xhr.onreadystatechange = function() {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    var responseText = xhr.responseText
                    callback(responseText)
                }
            }
        }
    </script>
</body>
</html>

(3)jQuery的ajax调用Promise的API

  1、首先下载引入jquery

    

     

   2、对比

之前使用jquery的ajax都是callback方式

    

接下来使用promise方式

    

     

接着调用

    

这里注意第二个then获取的是第一个的return返回值,无法获取第一个then的data数据,所以这需要新建对象

    

     接下来编写模板即可

    

 3、完整代码如下

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Promise应用场景举例--信息分类展示</title>
</head>
<body>
    <form id="user_form">
        
    </form>
    <script type="text/javascript" src="node_modules/art-template/lib/template-web.js"></script>
    <script type="text/template" id="tpl">
        <div>
            姓名:
            <input type="text" name="username" value="{{user.username}}">
        </div>
        <div>
            年龄:
            <input type="number" name="userage" value="{{user.age}}">
        </div>
        <div for="job">
            职业
            <select>
                {{each jobs}}
                    {{if $value.id === user.job}}
                        <option id="{{$value.id}}" selected>{{$value.name}}</option>
                        {{else}}
                        <option id="{{$value.id}}">{{$value.name}}</option>
                    {{/if}}
                {{/each}}
            </select>
        </div>
    </script>
    <script type="text/javascript" src="node_modules/jquery/dist/jquery.js"></script>
    <script type="text/javascript">
        var dataInfo = {}
        $.get('http://localhost:3000/users/2')
            .then(function(user){
                dataInfo.user = user
                return $.get('http://localhost:3000/jobs')
            })
            .then(function(jobs){
                dataInfo.jobs = jobs
                var htmlStr = template('tpl',dataInfo)
                document.querySelector('#user_form').innerHTML = htmlStr
            })
        /*
        旧版回调语法
        get('http://localhost:3000/users/2',function(usersData){
            get('http://localhost:3000/jobs',function(jobsData){
                var htmlStr = template('tpl',{
                    user:JSON.parse(usersData),
                    jobs:JSON.parse(jobsData)
                })
                document.querySelector('#user_form').innerHTML = htmlStr
            })
        })
        */
        /*自定义封装ajax
        function get(url,callback){
            var xhr;
            if (window.XMLHttpRequest) {
                xhr = new XMLHttpRequest()
            } else {
                xhr = new ActiveXObject("Microsoft.XMLHTTP")
            }
            xhr.open('get',url, true)
            xhr.send()
            xhr.onreadystatechange = function() {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    var responseText = xhr.responseText
                    callback(responseText)
                }
            }
        }
        */
    </script>
</body>
</html>

此时便成了链式调用

.

原文地址:https://www.cnblogs.com/jianxian/p/12269046.html