Promseチェーン:try catchでエラー対応

参考:Promseチェーン:try catchでエラー対応

Promise基本

let myFirstPromise = new Promise((resolve, reject) => {
  // We call resolve(...) when what we were doing asynchronously was successful, and reject(...) when it failed.
  // In this example, we use setTimeout(...) to simulate async code.
  // In reality, you will probably be using something like XHR or an HTML5 API.
  setTimeout( function() {
    resolve("Success!")  // Yay! Everything went well!
  }, 250)
})

myFirstPromise.then((successMessage) => {
  // successMessage is whatever we passed in the resolve(...) function above.
  // It doesn't have to be a string, but if it is only a succeed message, it probably will be.
  console.log("Yay! " + successMessage)
});

配列をPromise処理


//ループで処理を実行し、、かつ処理を「非同期処理として配列化」する
function unitLooP($unit){
   var relult = [];//promise配列用
//ループして処理をしつつ、処理は非同期扱いにする。
    for (var i = 0, l = $unit.length; i < l; i++) {
      console.log('ループ中');
      relult.push(setNja($unit[i]));
    }
   return relult;
}

//実行される関数を非同期処理化する。 resolve(成功した場合),
function setNja(el){
  return new Promise((resolve) => {
    let $op = {};
    $op.id = el.getAttribute('id');
    $op.type = el.getAttribute('data-type');
    retun resolve(setEditor($op));
  });
};

//実行関数
function setEditor(op) {
 //hogehoge
}


//配列化された非同期処理(Promise)がすべて実行完了したら、、then({ここが実行される})
//then(実行が成功した場合)
Promise.all(unitLooP($unit)).then(function() {
  var grid = new Muuri('#' + $areaid,$muriop);
});