0
0

LWC Javascript 非同期処理の確認

Posted at

SalesForceのLWCでJavascrpitを触るので、非同期処理を確認。

JavaScript Primer
https://jsprimer.net/basic/async/

Promiseを明示的に使うか、Async/awaitを使って同期処理的に書くか。
やっていることは同じ。

  
LWCでAPEXを呼び出すときは非同期処理。

Apex を使用したデータの操作
https://trailhead.salesforce.com/ja/content/learn/modules/lightning-web-components-and-salesforce-data/use-apex-to-work-with-data

命令的な Apex コール
handleButtonClick() {
    getContactsBornAfter({ //imperative Apex call
        birthDate: this.minBirthDate
    })
        .then(contacts => {
            //code to execute if related contacts are returned successfully
        })
        .catch(error => {
            //code to execute if related contacts are not returned successfully
        });
}

この例はPromiseを使った書き方なので、
Async/awaitに書き換えると...

命令的な Apex コール async書き換え
async handleButtonClick() {
  try {
    const contacts = await getContactsBornAfter({ birthDate: this.minBirthDate });
    //code to execute if related contacts are returned successfully
  } catch(e) {
    //code to execute if related contacts are not returned successfully
  }
}

どっちを使っても同じなのだが、連続してAPEXを呼び出すような場合だと「Async/await」を使った方がネストが深くならないので読みやすい。

0
0
0

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
0
0