順番に実行させる
複数の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
の引数)をもらっている。
(おまけ)名前について
resolve
をfulfill
と名付けている流派があるように見受けられる。
なので、resolve
をfulfill
とリネームした同様のソースが下記です。
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) })
他の流派としてresult
をvalue
やv
と名付けているのも見かける(?)。
この記事を書いた動機
下記のように書いてしまうと、期待した動作をしなかったためである。
ソース(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