0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

[JavaScript]Promiseからasync/awaitへの書き換え

Posted at

Promiseを用いた処理を,async/awaitを用いた処理に書き換える。

Promiseを用いた処理
getPost(postId)
    .then((post) => getUser(post.userId))
    .then((user) => getOrganization(user.orgId))
    .then((org) => {
        // 必要な処理
    });
async/awaitを用いた処理
const myFunc = async (postId) => {
    const post = await getPost(postId);
    const user = await getUser(post.userId);
    const org  = await getOrganization(user.orgId);
    // 必要な処理
  • 最初にgetPost(postId)を実行
  • その結果を得られ次第、getUser(post.userId)を実行

全ての操作が非同期で行われますが、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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?