Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
8
Help us understand the problem. What is going on with this article?
@shingo-nakanishi

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

More than 1 year has passed since last update.

順番に実行させる

複数の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
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
shingo-nakanishi
https://www.clear-lesson.com/

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
8
Help us understand the problem. What is going on with this article?