---
description: >-
  https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all
---

# Promise.all full (ok)

{% embed url="https://maruno-gp.cybozu.com/k/admin/app/37/plugin/config?pluginId=fdeplpmkengkldpdlaiegpokgmaabkkb" %}

**Bài toán**: có 3 giá trị Promise riêng biệt **gp, kosan, vanline** giờ tôi muốn gộp 3 giá trị này cùng 1 để xử lý 😉

D:\Tiah\working\MARUNO-21\smarthr.js

```javascript
(function() {
  function showSpinner() {
    // Initialize
    if ($('.kintone-spinner').length === 0) {
      // Create elements for the spinner and the background of the spinner
      const spin_div = $('<div id ="kintone-spin" class="kintone-spinner"></div>');
      const spin_bg_div = $('<div id ="kintone-spin-bg" class="kintone-spinner"></div>');
      // Append spinner to the body
      $(document.body).append(spin_div, spin_bg_div);
      const opts = {
        'color': '#000'
      };
      // Create the spinner
      new Spinner(opts).spin(document.getElementById('button-send-messenger-one'));
    }
    // Display the spinner
    $('.kintone-spinner').show();
  }
  function hideSpinner() {
    // Hide the spinner
    $('.kintone-spinner').hide();
  }
  const AppId = kintone.app.getId();
  function chunkArrayInGroups(arr, size) {
    var newArr = [];
    for (var i = 0; i < arr.length; i += size) {
      newArr.push(arr.slice(i, i + size));
    }
    return newArr;
  }
  function getUniqueListBy(arr, key) {
    return [...new Map(arr.map(item => [item[key], item])).values()]
  }
  function fetch(app_id, opt_query, opt_offset, opt_records) {
    var offset = opt_offset || 0;
    var records = opt_records || [];
    var query = opt_query || '';
    var id = app_id || kintone.app.getId();
    var params = {
      app: id,
      query: query + ' limit 500 offset ' + offset
    };
    return kintone.api('/k/v1/records', 'GET', params).then(function(resp) {
      records = records.concat(resp.records);
      if (resp.records.length === 500) {
        return fetch(id, query, offset + 500, records);
      }
      return records;
    });
  }
  kintone.events.on(['app.record.index.show'], async function(event) {
    if (document.getElementById('button-send-messenger-one') != null) {
      return;
    }
    var mySpaceFieldButtonOne = document.createElement('button');
    mySpaceFieldButtonOne.id = 'button-send-messenger-one';
    mySpaceFieldButtonOne.style = "margin-left: 10px;font-weight: 700;";
    mySpaceFieldButtonOne.innerHTML = 'Get Data from SmartHr';
    var bodyPost = {
      app: AppId,
      records: []
    };
    var bodyPut = {
      app: AppId,
      records: []
    };
    mySpaceFieldButtonOne.onclick = async function() {
      showSpinner(); // Display the spinner
      setTimeout(() => {
        hideSpinner(); // Hide the spinner
      }, (3000));
      var oldData = await fetch().then(function(records) {
        return records;
      });
      var empCode = oldData.map(i => i.社員番号.value);
      function fetchDatas(urlToken, opt_offset, opt_result, defer) {
        var offset = opt_offset || 1;
        var result = opt_result || [];
        return $.ajax({
          "url": urlToken+"&page=" + offset + "&per_page=100",
          "method": "GET",
          "timeout": 0,
          "headers": {
            "Content-Type": "application/json"
          },
          success: function(response) {
            result = result.concat(response);
            if (response.length == 100) {
              fetchDatas(urlToken,offset + 1, result, defer);
            } else {
              defer.resolve(result);
            }
          }
        });
      }
      function requestAll(urlToken) {
        var deferred = jQuery.Deferred();
        fetchDatas(urlToken,null, [], deferred);
        return deferred.promise();
      }
      var bodyPost = {
        app: AppId,
        records: []
      };
      var bodyPut = {
        app: AppId,
        records: []
      };
      var gp = requestAll('https://maruno-gp.smarthr.jp/api/v1/crews/?access_token=shr_62d9_K6PzVXJtqqz8pCm7g3zFUKLLut4irKuA');
      var kosan = requestAll('https://maruno-kosan.smarthr.jp/api/v1/crews/?access_token=shr_453a_Y7fnpCGs4p7P4GUSU5MdsFA3UgxynNkL');
      var vanline = requestAll('https://maruno-vanline.smarthr.jp/api/v1/crews/?access_token=shr_b27a_kH5uNXA4QUnQPCW6GiqVURjr5A6QYXEd');
      Promise.all([gp, kosan,vanline]).then( async function(values) {
        items = values.flat(1);
        items = getUniqueListBy(items, 'emp_code')
        items.forEach(function(element, index) {
          let emp_status = (element.emp_status == 'employed') ? "在職中" : (element.emp_status == 'retired') ? "退職済" : "休職中";
          let item = {
            "社員番号": {
              "value": element.emp_code
            },
            "氏": {
              "value": element.last_name
            },
            "氏カナ": {
              "value": element.last_name_yomi
            },
            "名": {
              "value": element.first_name
            },
            "名カナ": {
              "value": element.first_name_yomi
            },
            "部署": {
              "value": element.department
            },
            "役職": {
              "value": element.position
            },
            "在職状況": {
              "value": emp_status
            },
            "雇用形態": {
              "value": element.employment_type ? element.employment_type.name : null
            },
            "入社年月日": {
              "value": element.entered_at
            },
            "退職年月日": {
              "value": element.ontract_end_on
            },
            "生年月日": {
              "value": element.birth_at
            },
            "事業所": {
              "value": element.departments ? '丸野興産 ' + (element.departments[0].parent ? element.departments[0].parent.name : null) : null
            },
            "性別": {
              "value": element.gender == 'male' ? '男性' : '女性'
            },
            "氏名": {
              "value": element.last_name + element.first_name
            },
            "氏名カナ": {
              "value": element.first_name_yomi + element.last_name_yomi
            },
          };
          let tmp = oldData.find(i => (i.社員番号.value == element.emp_code));
          var findId = tmp ? tmp.$id.value : null;
          if (findId != null && element.emp_code != null) {
            let itemPut = {
              id: findId,
              record: item
            };
            bodyPut.records.push(itemPut);
          }
          if (findId == null && element.emp_code != null) {
            bodyPost.records.push(item);
          }
        });
        if (bodyPost.records.length > 0) {
          await chunkArrayInGroups(bodyPost.records, 100).reduce(async (promise, arr) => {
           await promise;
           var body = {
             'app': AppId,
             'records': arr
           };
           const resp = await kintone.api('/k/v1/records', 'POST', body);
         }, Promise.resolve());
        };
        if (bodyPut.records.length > 0) {
          await chunkArrayInGroups(bodyPut.records, 100).reduce(async (promise, arr) => {
           await promise;
           var body = {
             'app': AppId,
             'records': arr
           };
           const resp = await kintone.api('/k/v1/records', 'PUT', body);
         }, Promise.resolve());
        };
        location.reload(true);
      }).catch(function(err) {
        console.log(err);
        alert('社員情報を取得できません。ご確認ください。');
      });
    };
    kintone.app.getHeaderMenuSpaceElement().appendChild(mySpaceFieldButtonOne);
    return event;
  });
})();
```
