Promise.resolve()
メソッドは、与えられた値で解決した Promise
オブジェクトを返します。その値がプロミスであった場合は、そのプロミスが返されます。その値が thenable (すなわち "then" メソッド
を持っている場合) であれば、返されるプロミスは thenable を「追跡」し、その最終的な状態を採用します。それ以外の場合は、引数で満足したプロミスが返されます。この関数は複数階層のプロミス風オブジェクト (例えば、何かで解決するプロミスで解決するプロミス) を単一の階層に平坦化します。
構文
Promise.resolve(value);
引数
value
- この
Promise
で解決する際の引数。解決するためのPromise
または thenable にすることもできます。
返値
与えられた値で解決された Promise
、または value がプロミスオブジェクトであった場合、値として渡されたプロミスです。
解説
静的な Promise.resolve
関数は、解決する Promise
を返します。
例
静的な Promise.resolve メソッドの使用
Promise.resolve('Success').then(function(value) {
console.log(value); // "Success"
}, function(value) {
// not called
});
配列で解決
var p = Promise.resolve([1,2,3]);
p.then(function(v) {
console.log(v[0]); // 1
});
別の Promise で解決
var original = Promise.resolve(33);
var cast = Promise.resolve(original);
cast.then(function(value) {
console.log('value: ' + value);
});
console.log('original === cast ? ' + (original === cast));
// ログの順番:
// original === cast ? true
// value: 33
ログの順番が反転するのは、 then
ハンドラーが非同期に呼び出されるために発生します。 then
がどのように動作するのかはこちらを参照してください。
thenables で解決してエラーを発生させる
// Resolving a thenable object
var p1 = Promise.resolve({
then: function(onFulfill, onReject) { onFulfill('fulfilled!'); }
});
console.log(p1 instanceof Promise) // true, object casted to a Promise
p1.then(function(v) {
console.log(v); // "fulfilled!"
}, function(e) {
// not called
});
// Thenable throws before callback
// Promise rejects
var thenable = { then: function(resolve) {
throw new TypeError('Throwing');
resolve('Resolving');
}};
var p2 = Promise.resolve(thenable);
p2.then(function(v) {
// not called
}, function(e) {
console.error(e); // TypeError: Throwing
});
// Thenable throws after callback
// Promise resolves
var thenable = { then: function(resolve) {
resolve('Resolving');
throw new TypeError('Throwing');
}};
var p3 = Promise.resolve(thenable);
p3.then(function(v) {
console.log(v); // "Resolving"
}, function(e) {
// not called
});
仕様書
ブラウザーの互換性
BCD tables only load in the browser
互換性データに協力していただけるのであれば、 https://github.com/mdn/browser-compat-data に対してプルリクエストを書いてください。