LoginSignup
2
2

LWCでApexメソッドの呼び出しがたくさんあるなら、Promise.allを使おう

Last updated at Posted at 2023-09-15

はじめに

LWCからApexの呼び出しが色んな種類に渡って必要になること、あると思います。
例えばこんな感じに。

example.js
import { LightningElement, api } from 'lwc';

import isAdmin from '@salesforce/apex/ProfileUtil.isAdmin';
import isReadOnly from '@salesforce/apex/ExampleUtil.isReadOnly';
import getPickList from '@salesforce/apex/ObjectUtil.getPickList';
import getAccount from '@salesforce/apex/ExampleController.getAccount';

export default class Example extends LightningElement {
  @api
  accountId = '';

  isAdmin = false;
  isReadOnly = false;
  customColumnOptions = [];
  accountData = {};

  async connectedCallback() {
    this.isAdmin = await isAdmin({});
    this.isReadOnly = await isReadOnly({});
    this.customColumnOptions = await getPickList({object: 'Account', column: 'CustomColumn__c'});
    this.accountData = await getAccount({accountId: this.accountId});
  }
}

このとき、処理にかかる時間としては下記の通りになります。
image.png

Promise.allを使おう

Promise.allを使うことで、同期処理ではありながらも並行して(並列ではない)Apexメソッドを呼び出すことが出来ます。
Promise.all() - JavaScript | MDN

example.js
import { LightningElement, api } from 'lwc';

import isAdmin from '@salesforce/apex/ProfileUtil.isAdmin';
import isReadOnly from '@salesforce/apex/ExampleUtil.isReadOnly';
import getPickList from '@salesforce/apex/ObjectUtil.getPickList';
import getAccount from '@salesforce/apex/ExampleController.getAccount';

export default class Example extends LightningElement {
  @api
  accountId = '';

  isAdmin = false;
  isReadOnly = false;
  customColumnOptions = [];
  accountData = {};

  async connectedCallback() {
    const values = await Promise.all([
      isAdmin({})
      ,isReadOnly({})
      ,getPickList({object: 'Account', column: 'CustomColumn__c'})
      ,getAccount({accountId: this.accountId})
    ]);

    this.isAdmin = values[0];
    this.isReadOnly = values[1];
    this.customColumnOptions = values[2];
    this.accountData = values[3];
  }
}

並行して処理を呼び出すことで、手前の処理の終了を待つ必要がなく時間が短縮されます。
image.png

おまけ:JavaScriptの並行処理について

JavaScriptはシングルスレッドなので、並列処理は出来ません。
そのため、上記の通り並行処理という書き方になるようです。

並列処理のイメージ

4人の相手とキャッチボールするために、4人に分身する。
1人の相手に対して1人がいるため、キャッチボールが可能となる。

並行処理のイメージ

4人の相手とキャッチボールするために、すごい勢いでボールを投げ返したり体の向きを変える。
厳密に見ればそれぞれラグが発生しているが、素早く対応する相手を切り替えることで同時にキャッチボールしているかのように感じさせている。

間違ってたらご指摘ください・・。

おわりに

全人類使おう。Promise.all
おじさんとの約束だ。

2
2
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2