# １件読込み１件更新を繰り返したい

**URL:** <https://community.cybozu.dev/t/topic/5382>\
**Category:** kintone 開発相談\
**Created:** [October 19, 2021, 7:12am UTC](https://community.cybozu.dev/t/topic/5382 "2021-10-19T07:12:24Z")\
**Posts on this page:** 5\
**Page:** 1

<div class="post-metadata">

**Author:** ![Legacy\_Account392](https://avatars.discourse-cdn.com/v4/letter/l/ecc23a/32.png) [@Legacy\_Account392](https://community.cybozu.dev/u/Legacy_Account392)\
**Post date:** [October 19, 2021, 7:12am UTC](https://community.cybozu.dev/t/topic/5382/1 "2021-10-19T07:12:24Z")

</div>

あるファイルのフラグを一括で更新したいのですが、

レコードの一括更新のＡＰＩ説明には

ひとつずつ配列に記述してputとなっています

[https://developer.cybozu.io/hc/ja/articles/201941784#step2](https://community.cybozu.dev/hc/ja/articles/201941784#step2)&nbsp;

&nbsp;

ファイルを１件読み込んで更新という方法をしたくてコードを組みましたが

結果はうまく行ったのですが、JSEdit for kintoneのﾜｰﾆﾝｸﾞｴﾗｰで

「Dont’ make functions with in a loop」

と表示されるのでダメな記述なんだろうなと思っています。

結果は全部更新されていますが、動きの順番が？？です。

console.log で結果を見るとなぜこんな動きなのか。

&nbsp;

どう書くのが正しいのでしょうか？

&nbsp;

また、更新した件数をreturnで戻し、その値で再表示を行いたいのですが

読込みや更新の前にreturn処理が行われ、件数を受け取れません。

&nbsp;

↓console結果

kintone.events.on(‘app.record.index.show’, function (event) {  
&nbsp; let vButton = document.getElementById(‘button’)

&nbsp; //一括ｵﾌ ｸﾘｯｸ時  
&nbsp; vButton.onclick = function () {

&nbsp; &nbsp; _**console.log(“onclick 1”);**_  
&nbsp; &nbsp; vPutCnt = ApKanriAllPut(0) ;  
&nbsp; &nbsp; _**console.log(“onclick 2”);**_

&nbsp; &nbsp; if (vPutCnt \> 0) {  
&nbsp; &nbsp; &nbsp;&nbsp; location.reload();  
&nbsp; &nbsp; }

&nbsp; &nbsp; return ;  
&nbsp; }  
});

function ApKanriAllPut(vFlg){  
&nbsp; let vPutCnt = 0 ;

&nbsp; //自分のｱﾌﾟﾘID  
&nbsp; let vMyId = kintone.app.getId() ;

&nbsp; //ﾊﾟﾗﾒｰﾀ  
&nbsp; let requestParam = {  
&nbsp; &nbsp; &nbsp; ‘app’: vMyId ,  
&nbsp; &nbsp; &nbsp; ‘query’: kintone.app.getQuery()  
&nbsp; };

&nbsp; _**console.log(“Get Mae”);**_

&nbsp; //対象のﾚｺｰﾄﾞを読み込む  
&nbsp; kintone.api(kintone.api.url(‘/k/v1/records’, true), ‘GET’, requestParam,  
&nbsp; function(resp) {  
&nbsp; &nbsp; for (let i=0 ; i \< resp.records.length ; i++) {  
&nbsp; &nbsp; &nbsp;&nbsp; let vRecId = resp.records[i].レコード番号.value ;

&nbsp; &nbsp; &nbsp;&nbsp; //ﾊﾟﾗﾒｰﾀ  
&nbsp; &nbsp; &nbsp;&nbsp; let requestParam1 = {  
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ‘app’: vMyId ,  
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ‘id’: vRecId ,  
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ‘record’: {  
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; ‘フラグ’: {‘value’: vFlg&nbsp; }  
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }  
&nbsp; &nbsp; &nbsp;&nbsp; };

&nbsp; &nbsp; &nbsp; _**console.log(“i=” + i + " " +“id=” + vRecId) ;**_

&nbsp; &nbsp; &nbsp;&nbsp; //指定ﾚｺｰﾄﾞIDを更新する  
&nbsp; &nbsp; &nbsp;&nbsp; kintone.api(kintone.api.url(‘/k/v1/record’, true), ‘PUT’, requestParam1,  
&nbsp; &nbsp; &nbsp; &nbsp;&nbsp; function(resp1) {  
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; _**console.log(“i=” + i + " " + “PUT OK” + " Recid=" + vRecId) ;**_  
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; vPutCnt = vPutCnt + 1 ;  
&nbsp; &nbsp; &nbsp; &nbsp;&nbsp; } ,  
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; function(err1) {  
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; console.log(“PUT NG”) ;  
&nbsp; &nbsp; &nbsp; &nbsp;&nbsp; }  
&nbsp; &nbsp; &nbsp;&nbsp; );  
&nbsp; &nbsp; }  
&nbsp; } ,  
&nbsp; function(err) {  
&nbsp; &nbsp;&nbsp; console.log(“GET NG”) ;  
&nbsp; }  
)

_**console.log(“Return Mae=” + vPutCnt);**_

return vPutCnt ;  
}

---

<div class="post-metadata">

**Author:** ![Legacy\_Account2476](https://avatars.discourse-cdn.com/v4/letter/l/c0e974/32.png) [@Legacy\_Account2476](https://community.cybozu.dev/u/Legacy_Account2476)\
**Post date:** [October 21, 2021, 9:49am UTC](https://community.cybozu.dev/t/topic/5382/2 "2021-10-21T09:49:21Z")

</div>

ちゃいな嬢 様

&nbsp;

JSEdit for kintone から「Dont’ make functions with in a loop」 表示されるように現状ですとレコード数が多くなった場合にリクエスト過多によりエラーが発生するかもしれません。

&nbsp;

対処方法として、async/await 利用すると順番通り処理されるのではないかと思います。

[目指せ！JavaScriptカスタマイズ中級者（２） 〜Promiseのかわりにasync/await編〜 – cybozu developer network](https://community.cybozu.dev/hc/ja/articles/900001244323-%E7%9B%AE%E6%8C%87%E3%81%9B-JavaScript%E3%82%AB%E3%82%B9%E3%82%BF%E3%83%9E%E3%82%A4%E3%82%BA%E4%B8%AD%E7%B4%9A%E8%80%85-%EF%BC%92-Promise%E3%81%AE%E3%81%8B%E3%82%8F%E3%82%8A%E3%81%ABasync-await%E7%B7%A8-)

&nbsp;

サンプルとして記述の変更内容を置いておきますので、上記URLの内容からasync/awaitを勉強して頂ければと思います。

基本は、fanction定義の前に async を置き、非同期処理の前に await を置くような感じになると思います。

沢山、ネット上にありますので記述を読んで勉強して頂けれ幸いでございます。

```
(function () {
  "use strict";
  kintone.events.on("app.record.index.show", function (event) {
    let vButton = document.getElementById("button");

    //一括ｵﾌ ｸﾘｯｸ時
    vButton.onclick = async function () {
      console.log("onclick 1");
      let vPutCnt = await ApKanriAllPut(0);
      console.log("onclick 2");
      if (vPutCnt > 0) {
        location.reload();
      }

      return;
    };
 });

 async function ApKanriAllPut(vFlg) {
    let vPutCnt = 0;

    //自分のｱﾌﾟﾘID
    let vMyId = kintone.app.getId();

    //ﾊﾟﾗﾒｰﾀ
    let requestParam = {
      app: vMyId,
      query: kintone.app.getQuery(),
    };

    console.log("Get Mae");

    //対象のﾚｺｰﾄﾞを読み込む
    await kintone.api(kintone.api.url("/k/v1/records", true), "GET", requestParam).then(
      async function (resp) {
        for (let i = 0; i < resp.records.length; i++) {
          let vRecId = resp.records[i].レコード番号.value;

          //ﾊﾟﾗﾒｰﾀ
          let requestParam1 = {
            app: vMyId,
            id: vRecId,
            record: {
              フラグ: { value: vFlg },
          },
        };
        console.log("i=" + i + " " + "id=" + vRecId);

          //指定ﾚｺｰﾄﾞIDを更新する
          await kintone.api(kintone.api.url("/k/v1/record", true), "PUT", requestParam1).then(
            function (resp1) {
              console.log("i=" + i + " " + "PUT OK" + " Recid=" + vRecId);
              vPutCnt = vPutCnt + 1;
            },
            function (err1) {
              console.log("PUT NG");
            }
          );
        }
      },
      function (err) {
        console.log("GET NG");
      }
    );
    console.log("Return Mae=" + vPutCnt);
    return vPutCnt;
  }
})();

```

&nbsp;

また、JSEdit for kintoneのエラー等が気になるようでしたら、一括更新などを利用されるとよいかと思います。

ちゃいな嬢 様と同じ内容の動きをするサンプルを下記に置いておきます。

※function ApKanriAllPut は JSEdit for kintoneでは名前をクラス等と間違って警告がでますので、『apKanriAllPut』へ変更しております。

```
(function () {
  "use strict";

  function apKanriAllPut(vFlg, event) {
    let records = event.records;
    let putRecords = [];
    for(let i = 0; records.length > i; i++) {
      let rec = records[i].レコード番号.value;
      let put = {
        "id": rec,
        "record": {
          "フラグ": {"value": vFlg}
        }
      };
      putRecords.push(put);
    }
    let requestParam = {
      "app": kintone.app.getId(),
      "records": putRecords
    };
    kintone.api(kintone.api.url("/k/v1/records", true), "PUT", requestParam, function (resp) {
      location.reload();
    }, function (err) {
      console.log("PUT NG", err.message);
    });
  }

  kintone.events.on("app.record.index.show", function (event) {
    let vButton = document.getElementById("button");

    //一括ｵﾌ ｸﾘｯｸ時
    vButton.onclick = function () {
      if(!event.records[0]) {
        return alert("レコードがありません");
      }
      apKanriAllPut(0, event);
      return;
    };
  });
});

```

---

<div class="post-metadata">

**Author:** ![Legacy\_Account392](https://avatars.discourse-cdn.com/v4/letter/l/ecc23a/32.png) [@Legacy\_Account392](https://community.cybozu.dev/u/Legacy_Account392)\
**Post date:** [October 22, 2021, 2:39am UTC](https://community.cybozu.dev/t/topic/5382/3 "2021-10-22T02:39:13Z")

</div>

新屋さま

ありがとうございます！&nbsp; 少しずつ勉強していて、async/await かなとまでは

たどり着いたけど意味が理解できず困っていました。

非同期だけど待つ？の意味が・・非同期って待たずに実行ですよね？

日本人ですが日本語が？？ってなってました。ネットで書いてるのを勉強してても

難しいです。もう動かして理解するしかないですね。

結局その処理が終わるまで次の処理をしたくない時にasync/await を使用するのですよね？

処理Ａ

関数Ｂ

処理ｃ

で関数Ｂの結果をｃで使用したい場合とか？

一括更新もありがとうございます！

最初のコードは記述して想定通りに行くことを確認しました。

一括更新も試してみます！

ほんと丁寧な回答に感謝します。

---

<div class="post-metadata">

**Author:** ![Legacy\_Account2476](https://avatars.discourse-cdn.com/v4/letter/l/c0e974/32.png) [@Legacy\_Account2476](https://community.cybozu.dev/u/Legacy_Account2476)\
**Post date:** [October 22, 2021, 4:32am UTC](https://community.cybozu.dev/t/topic/5382/4 "2021-10-22T04:32:16Z")

</div>

ちゃいな嬢 様

&nbsp;

概ね私の理解も似たようなものです。

およそ1ヵ月前に、あれ順番通りに処理されない・・・から始まり、Promise ってなんだろうという感じで必死に本やネットの記述を読まくりました。

結局、自分で記述して動きを見て検証して納得するってことを繰り返しています。

【動かして理解する】ってことに本当にその通りだなと感じているところです。

async/await も今回のちゃいな嬢 様の内容をみて初めて試してなんとなく理解した程度です。

&nbsp;

私の拙い回答で納得していただけたようで良かったです。

---

<div class="post-metadata">

**Author:** ![Legacy\_Account392](https://avatars.discourse-cdn.com/v4/letter/l/ecc23a/32.png) [@Legacy\_Account392](https://community.cybozu.dev/u/Legacy_Account392)\
**Post date:** [October 22, 2021, 5:39am UTC](https://community.cybozu.dev/t/topic/5382/5 "2021-10-22T05:39:01Z")

</div>

新屋さま

javascriptを初めて触ったのが8月下旬・・そしてkintone用を触り始めたのが9月中旬過ぎ

右も左もわからない状態で奮闘し、ここの質問を活用させてもらい理解を深めています。

そして修正したらIEでは動かないことを理解しました。

EdgeとIEで裏表みたいに使用していたので。

奥深い事多いですが勉強になりました！
