LoginSignup
4
10

More than 1 year has passed since last update.

Promiseのシンプルな書き方メモ

Last updated at Posted at 2018-02-09

いつもPromise書こうとした時に、書き方忘れるのでメモ

ポイントは、

  • promiseの呼び出し方を見た目シンプルにする
  • 非同期処理(taskA,taskB,taskC)を同期処理させる
  • それぞれの処理結果を渡していく
  • require(promiseライブラリ)は使わない前提

// 以下のpromise関数不要でした
// Promiseの呼び出し関数
// const promise = (v) =>
//  new Promise((resolve, reject) => {
//    resolve(v);
//  }
// );

// 非同期処理taskA
const taskA = (v) => {
  return new Promise((resolve, reject) => {
    console.log("taskA",v);
    v = v+1;
    resolve(v);
  });
}


// 非同期処理taskB
const taskB = (v) => {
  return new Promise((resolve, reject) => {
    console.log("taskB",v);
    v = v+1;
    resolve(v);
  });
}

// 非同期処理taskC
const taskC = (v) => {
  return new Promise((resolve, reject) => {
    console.log("taskC",v);
    resolve(v);
  });
}

// エラー処理
const onRejectted = (v)=>{
  console.log("onRejectted",v);
}

// -----------
// メイン処理
// -----------

// promise(1) // まずPromiseの最初の呼び出し部分は引数渡すだけにする
Promise.resolve(1) // まずPromiseの最初の呼び出し部分は引数渡すだけにする
.then(taskA) // 次にthenで各非同期処理を呼び出す
.then(taskB)
.then(taskC)
.catch(onRejectted);

実行結果

$ node simple_promise.js
taskA 1
taskB 2
taskC 3

Promiseの書き方(見た目)が分かりにくいので、直感的に分かり易くなるよう意識しました。

4
10
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
4
10