LoginSignup
32
31

More than 5 years have passed since last update.

Promiseテンプレート

Last updated at Posted at 2016-07-25

Promiseとは

Promiseは非同期処理を抽象化したオブジェクトとそれを操作する仕組みの事をいいます。

参考:JavaScript Promiseの本

このエントリーは?

Promiseについていろいろ勉強した結果、 自分のなかでこういう書き方がわかりやすいかなぁとまとめた内容です。
今後も使いそうなのでテンプレートにしておきました。

ソース

Promise処理を順番に処理したい場合

promise.js
call_async_process.process_A(params)
  .then(function(value) {

    // 成功時:何か処理

    // 次の関数の引数
    return proaRes
  })
  .then(call_async_process.process_B)
  .then(function(value) {

    // 成功時:何か処理

    // 次の関数の引数
    return probRes
  })
  .then(call_async_process.process_C)
  .then(function(value) {

   // 成功時:何か処理

  }).catch(function(reason) {
    // 失敗時の処理
    // ※上記で呼び出したすべての非同期処理のreject結果が入る
  });

Promise処理が全て終わるのを待つ場合

promiseAll.js
/**
 * call_async_processの3つの非同期処理を監視
 * @class process_promise_all
 * @return {Promise} Promiseオブジェクト
 */
const process_promise_all = {
  return Promise.all([
    call_async_process.process_A(),
    call_async_process.process_B(),
    call_async_process.process_C()
  ]);
}

// 実行
process_promise_all().then(function (value) {
    //成功
    console.log(value);
}).catch(function(reason){
    //失敗
    console.log(reason);
});

非同期処理呼び出しの部分

call_async_process.js
/**
 * 非同期処理群
 * @class call_async_process
 */
const call_async_process = {
  /**
   * 処理A
   * @memberof call_async_process
   * @return {Promise} Promiseオブジェクト
   */
  process_A() {
      return new Promise(function(resolve, reject) {

        /**
         *  非同期処理呼び出し A
         * @memberof call_async_process.process_A
         */
        startAjax(urlparam)
          .done(function(data) {

            if ('エラーとしたい戻り値判定') {
              resolve('success');
            } else {
              reject('error');
            }

          }).fail(function(XMLHttpRequest, textStatus, errorThrown) {
            reject(errorThrown);
          })
      });
    },
    /**
     * 処理B
     * @memberof call_async_process
     * @return {Promise} Promiseオブジェクト
     */
    process_B() {
      return new Promise(function(resolve, reject)
       //call_async_process.process_Aと同じ感じ
      });
    },
    /**
     * 処理C
     * @memberof call_async_process
     * @return {Promise} Promiseオブジェクト
     */
    process_C(params/*引数あり*/) {
      return new Promise(function(resolve, reject) {
        //call_async_process.process_Aと同じ感じ
      })
    }
};

内部のajax処理(非同期処理)

startAjax.js
/**
 * Ajax処理
 * @function startAjax
 * @return {Promise} Promiseオブジェクト
 */
function startAjax(urlparam) {
    return $.ajax({
        url: "http://" + urlparam,
        type: "POST",
        dataType: "xml",
        contentType: "text/xml; charset=\"utf-8\"",
        connection: "Keep-Alive",
        crossDomain: true,
        headers: {
            SOAPAction: "urn:init"
        },
        data: soapMessage
    })
}
32
31
2

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
32
31