LoginSignup
8
8

More than 5 years have passed since last update.

Promiseで順番に実行したいとき

Last updated at Posted at 2018-09-08

順番に実行させる

複数のPromiseを順番に実行させる方法を載せる。

ソース(JavaScript)

function onFulfilled() {
    return function(result) {
      return new Promise(function(resolve, reject) {
        console.log(result)
        setTimeout(function(){ resolve("Hello"); }, 1000);
      });
    }
};

Promise.resolve("first")
       .then(onFulfilled())
       .then(onFulfilled())
       .then(onFulfilled())
       .then((result) => { console.log(result) })

結果

> "first"
> "Hello"
> "Hello"
> "Hello"

ちょっとした説明(?)

onFulfilled
Promiseを作って返す関数」を返す関数。

仮引数 resultは前のPromiseの結果(つまりresolveの引数)をもらっている。

(おまけ)名前について

resolvefulfillと名付けている流派があるように見受けられる。
なので、resolvefulfillとリネームした同様のソースが下記です。

function onFulfilled() {
    return function(result) {
      return new Promise(function(fulfill, reject) {
        console.log(result)
        setTimeout(function(){ fulfill("Hello"); }, 1000);
      });
    }
};

Promise.resolve("first")
       .then(onFulfilled())
       .then(onFulfilled())
       .then(onFulfilled())
       .then((result) => { console.log(result) })

他の流派としてresultvaluevと名付けているのも見かける(?)。

この記事を書いた動機

下記のように書いてしまうと、期待した動作をしなかったためである。

ソース(JavaScript)

function onFulfilled() {
    return new Promise(function(resolve, reject) {
        console.log(result)
        setTimeout(function(){ resolve("Hello"); }, 1000);
    });
};

Promise.resolve("first")
       .then(onFulfilled())
       .then(onFulfilled())
       .then(onFulfilled())
       .then((result) => { console.log(result) })

結果

> "first"

(おまけ)async / await で書く

ソース(JavaScript)

function promiseFactory(result) {
  return new Promise(function(resolve, reject) {
    console.log(result)
    setTimeout(function(){ resolve("Hello"); }, 1000);
  });
}

async function hoge() {
  var result = await Promise.resolve("first")
  result = await promiseFactory(result)
  result = await promiseFactory(result)
  result = await promiseFactory(result)
  console.log(result)
}

hoge();

結果

> "first"
> "Hello"
> "Hello"
> "Hello"

Swift4, PromiseKit6.2.1 で同様の処理

ソース

import UIKit
import PromiseKit

class ViewController: UIViewController {
    func onFulfilled() -> (String) -> Promise<String> {
        return { result in
            return Promise<String> { seal in
                print(result)
                DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1), execute: {
                    seal.fulfill("Hello")
                })
            }
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        _ = Promise.value("first")
            .then(onFulfilled())
            .then(onFulfilled())
            .then(onFulfilled())
            .done { result in print(result) }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

結果

first
Hello
Hello
Hello

参考

8
8
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
8
8