向JSON对象添加详细信息:Javascript函数和承诺

时间:2018-03-17 23:57:37

标签: javascript function promise

我有以下结构:

公司有只有emp的员工名单。 另一个Util函数将提供emp列表中的emp详细信息。 如果存在细节,我需要编写一个将详细信息附加到匹配的emp ID的函数。

我的jsbin项目:http://jsbin.com/bacasuzixa/edit?html,js,output

        //jshint esnext:true
    function write(message) {
        document.getElementById('message').innerHTML += message + '<br/>';
    }
    function newParagraph() { 
      write("");
    }

    var PartialResponse=
    {

        "data": [
            {
                "company": "aaaa",
                "employees": [
                    {
                        "empid": "1"
                    },
                    {
                        "empid": "2"
                    },
                    {
                        "empid": "3"
                    }
                ]
            },
            {
                "company": "bbbb",
                "employees": []
            }
        ]
    }

    let queryEmps = new Promise((resolve, reject) => {
      setTimeout(function(){
        resolve(
          {

            "EmpProfile": {
              "Details": [
                {

                  "empid": "1",

                  "details": {
                    "email": "aaaa@bb.com",
                    "firstName": "aaaa"
                  }
                },
                 {
                  "empid": "2",
                  "details": {
                    "email": "ccc@ddd.com",
                    "firstName": "ccc"
                  }
                } 
              ]
            }
          }

        ); // Yay! Everything went well!
      }, 1);
    });


    newParagraph();

    newParagraph();

    function adEmployeeDetails( PartialResponse)
        {
                for (let i = 0, len = PartialResponse.data.length; i < len; i++) {
                if(PartialResponse.data[i].employees.length>0){
                    let empids = PartialResponse.data[i].employees.map(a => a.empid);
                    //returns array of Details
                    queryEmps
                    .then(response =>addDetails(response,PartialResponse.data[i].employees))
                    .then(response => write("LOCATION1 : PartialResponse: " + JSON.stringify(PartialResponse)))
                    /*
                    LOCATION1: Wanted result: 
                    {
                    "data": [
                        {
                        "company": "aaaa",
                        "employees": [
                            {
                            "empid": "1",
                            "profile": {
                                "email": "aaaa@bb.com",
                                "firstName": "aaaa"
                            }
                            },
                            {
                            "empid": "2",
                            "profile": {
                                "email": "ccc@ddd.com",
                                "firstName": "ccc"
                            }
                            },
                            {
                            "empid": "3"
                            }
                        ]
                        },
                        {
                        "company": "bbbb",
                        "employees": []
                        }
                    ]
                    }
                    */


                }
                //LOCATION2
    //             write("LOCATION2 : PartialResponse: " + JSON.stringify(PartialResponse));
            }   
            //LOCATION3
    //       write(LOCATION3 : PartialResponse: " + JSON.stringify(PartialResponse));
            return PartialResponse;
        }   

    function addDetails(userinfo,varEmployees){
      for (var i = 0, len = varEmployees.length; i < len; i++) {
        userinfo.EmpProfile.Details.forEach(
          function(childItem) {
            if ((childItem.empid == varEmployees[i].empid)) {
              varEmployees[i].profile = childItem.details;
            }
          });
      }
        return varEmployees;
    }

    newParagraph();
    //LOCATION4
    write("adEmployeeDetails: " +  
    JSON.stringify(adEmployeeDetails(PartialResponse)));

我希望LOCATION1上显示的结果转移到LOCATION2,LOCATION3并最终转移到LOCATION4。我不确定我错过了什么..

我的jsbin项目:http://jsbin.com/bacasuzixa/edit?html,js,output

我不是Javascript的专家。谢谢你的帮助......

1 个答案:

答案 0 :(得分:0)

您似乎希望从承诺中获得最终结果,并使用结果做某事,对吗?

让我们假设您想要实现的目标是:

  1. 获取员工列表(代码中的PartialResponse)
  2. 获取员工个人资料列表(代码中的queryEmps)
  3. 并且这两个数据都返回为Promise

    1. 合并员工及其个人资料。
    2. 显示结果(或您想要做的任何事情)。
    3. 可能的方法是使用Promise.all

      // Suppose that we have two functions which return 'Promise'
      fetchEmployee()
      fetchEmployeeDetail()
      

      使用Promise.all获取数据

      Promise.all([
        fetchEmployee(),
        fetchEmployeeDetail(),
      ])
      

      合并数据

      Primise.all([
        fetchEmployee(),
        fetchEmployeeDetail(),
      ])
      .then(result => {
        // The result is an array, and the order of the element in 
        // this array is the order of the Promise that 
        // you passed to Promise.all
        let listOfEmployee = result[0];
        let listOfDetail = result[1];
      
        // Do your combination logic here.
      
        return result; // Return the result that you combined here.
      })
      

      使用您已完成的工作

      Primise.all([
        fetchEmployee(),
        fetchEmployeeDetail(),
      ])
      .then(results => {
        // The result is an array, and the order of the element in 
        // this array is the order of the Promise that 
        // you passed to Promise.all
        let listOfEmployee = results[0];
        let listOfDetail = results[1];
      
        // Do your combination logic here.
      
        return result; // Return the result that you combined here.
      })
      .then(result => {
        // the result here is what you have combined in the previous step.
        // You can do anything you want here
      })
      

      以下是您的示例: JSBin example