LoginSignup
6
6

More than 5 years have passed since last update.

promise - asynchronous process

Last updated at Posted at 2015-04-09

What is promise?

非同期処理を抽象化したオブジェクトとそれを操作する仕組みのこと.
複雑な非同期処理等をうまくパターン化できるというのがPromiseの役割

promise-workflow.js
var Promise = require('promise');

function asyncFunction () {
  return new Promise(function (resolve, reject) {
    setTimeout(function () {
      resolve('Async Hello World');
    }, 10000);
  });
}

asyncFunction().then(function (value) {
  console.log(value);
}).catch(function (error) {
  console.log(error);
});

Memo

Javascriptにおける非同期処理といえば,コールバックを利用する場合が多い.

Sample

sample.js
var Promise = require('promise');

function taskA() {
  console.log("Task A");
  return 2;
}
function taskB(value) {
  console.log("Task B");
  return value * 2;
}
function onRejected(error) {
  console.log("Catch Error: A or B", error);
}
function finalTask() {
  console.log("Final Task");
}
function output (value) {
  console.log(value);
}
var promise = Promise.resolve();
promise
  .then(taskA)
  .then(taskB)
  .then(output)
  .catch(onRejected)
  .then(finalTask, onRejected);

Promise.all and Promise.race

Promise.all: Promise の and
渡した全てのpromiseがFulFilled または Rejectedになるまで次の処理を待つ.

Promise.race: Promise の or
どれか一つでもpromiseがFulFilled または Rejectedになったら次の処理を実行する

sample.js
var Promise = require('promise');

var winnerPromise = new Promise(function (resolve) {
  setTimeout(function () {
    console.log('this is winner');
    resolve('this is winner');
  }, 4);
});
var loserPromise = new Promise(function (resolve) {
  setTimeout(function () {
    console.log('this is loser');
    resolve('this is loser');
  }, 1000); });
// 一番最初のものがresolveされた時点で終了
Promise.race([winnerPromise, loserPromise]).then(function (value) {
console.log(value);    // => 'this is winner'
});
6
6
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
6
6