taquaki-satwo
11/29/2017 - 7:07 AM

Promise

JS-Promise

// 非同期処理1
console.log('A');
setTimeout(function() {console.log('B');}, 0);
console.log('C');
-> "A" "C" "B"

// 非同期処理2
function sleep(callback) {
  setTimeout(function() {
    callback();
  }, 1000);
}

sleep(function() {
  console.log("A");
  sleep(function() {
    console.log("B");
    sleep(function() {
      console.log("C");
    })
  })
})

// Promise #1
const promise1 = new Promise(function (resolve, reject) {
  setTimeout(function () {
    console.log('A');
    resolve();
  }, 1000);
});

promise1.then(function () {
  console.log('B');
})

// Promise #2
const promise2 = new Promise(function (resolve, reject) {
  setTimeout(function () {
    // let n = parseInt(prompt('10以下の数を入力してください'));
    if (n <= 10) {
      resolve(n);
    } else {
      reject(`エラー: ${n}は10以上です`);
    }
  }, 1000);
});

promise2
  .then(function (n) {
    console.log(`2^${n} = ${Math.pow(2, n)}`);
  })
  .catch(function (error) {
    console.log(error);
  });

// 別の書き方
promise2.then(
  function(n) {
    console.log(`2^${n} = ${Math.pow(2, n)}`);
  },
  function(error) {
    console.log(error);
  }
)