Help us understand the problem. What is going on with this article?

PromiseKit

More than 1 year has passed since last update.

4秒後にさらに2秒後の処理

Promise<String> { (fulfill, reject) in
    DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(4), execute: {
        print("fulfill 1")
        fulfill("FFF")
        print("fulfill 2")
    })
    }.then {_ in
        Promise<String> { (fulfill, reject) in
            DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(2), execute: {
                print("fulfill 3")
                fulfill("FFF")
                print("fulfill 4")
            })
        }
}

print("AAA")

結果

AAA
fulfill 1
fulfill 2
fulfill 3
fulfill 4

変数化してみようとしたけど、同時に走ってしまう

書き方を知らないだけかもしれないが下記のように、変数に代入すると同時に走ってしまった。

let p1 = Promise<String> { (fulfill, reject) in
    DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(4), execute: {
        print("fulfill 1")
        fulfill("FFF")
        print("fulfill 2")
     })
}

let p2 = Promise<String> { (fulfill, reject) in
    DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(2), execute: {
        print("fulfill 3")
        fulfill("FFF")
        print("fulfill 4")
    })
}

print("AAA")

なぜ上記のように変数に入れたかったかというと次のように書けるのではないかと思ったから、
しかし、同時に処理は走ってしまった。

p1.then { _ in p2 }

関数化することでやりたかったことに近いことができる

func p1() -> Promise<String> {
    return Promise<String> { (fulfill, reject) in
        DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(4), execute: {
            print("fulfill 1")
            fulfill("FFF")
            print("fulfill 2")
        })
    }
}

func p2() -> Promise<String> {
    return Promise<String> { (fulfill, reject) in
        DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(2), execute: {
            print("fulfill 3")
            fulfill("FFF")
            print("fulfill 4")
        })
    }
}

p1().then { [weak self] _ -> Void in
     guard let weakSelf = self else { return }

     _ = weakSelf.p2()
}
shingo-nakanishi
https://www.clear-lesson.com/
https://www.clear-lesson.com/
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