LoginSignup
0
0

More than 3 years have passed since last update.

【JavaScript】promise/then を async/await に書き換えるとこうなる。【非同期処理】

Last updated at Posted at 2020-07-25

あらすじ

世の中はまだまだPromise/then方式のドキュメントが多く、
シンプルにasync/awaitで書きたいときに混乱するので、変換方法をまとめました。

登場人物

function bePromise() { /*今回実行したい非同期処理(=Ajaxなど)*/ } 
function isSuccess() { /*bePromise()が成功か失敗か判断する処理*/ }
function ifSuccess() { /*bePromese()が成功した際に実行したい処理*/ } 
function ifFailure() { /*bePromese()が失敗した際に実行したい処理*/ } 

let responseData; // bePromise()が成功した際の返り値
let errorData; // bePromise()が失敗した際のエラーの内容

Promise / then

function(){
  bePromise()
    .then( (responseData)=>{
      ifSuccess();
    }
    .catch( (errorData)=>{
      ifFailure();
    });
}

async / await

変数定義方式

async function(){
  const responseData = await bePromise();
  if( isSuccess() ){
    ifSuccess();
  }else{
    ifFailure();
  }
}

メソッドチェーン方式

async function(){
  await bePromise()
    .then( (responseData)=>{
      ifSuccess();
    })
    .catch( (errorData)=>{
      ifFailure();
    });
}

try/catch方式

async function(){
  try{
    const responseData = await bePromise();
    ifSuccess();
  }catch(errorData){
    ifFailure();
  }
}

補足

今回のようにbePromise()の後に続く処理が
ひとつの関数にまとめられている場合、

.then( (responseData)=>{
  ifSuccess();
})
.catch( (errorData)=>{
  ifFailure();
});

のようになっている部分を、

.then( ifSuccess )
.catch( ifFailure );

のように、シンプルにまとめることが出来ます。

感想

失敗時の処理をどのくらい細かく扱いたいかによって、
いろんな書き方ができるんだなあと思いました。

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