--- title: Promise.resolve() slug: Web/JavaScript/Reference/Global_Objects/Promise/resolve tags: - ECMAScript 2015 - JavaScript - Method - Promise - Reference translation_of: Web/JavaScript/Reference/Global_Objects/Promise/resolve ---
Promise.resolve()
メソッドは、与えられた値で解決した {{jsxref("Promise")}} オブジェクトを返します。その値がプロミスであった場合は、そのプロミスが返されます。その値が thenable (すなわち {{jsxref("Promise.then", "\"then\" メソッド")}} を持っている場合) であれば、返されるプロミスは thenable を「追跡」し、その最終的な状態を採用します。それ以外の場合は、引数で満足したプロミスが返されます。この関数は複数階層のプロミス風オブジェクト (例えば、何かで解決するプロミスで解決するプロミス) を単一の階層に平坦化します。
Promise.resolve(value);
value
Promise
で解決する際の引数。解決するための Promise
または thenable にすることもできます。与えられた値で解決された {{jsxref("Promise")}}、または value がプロミスオブジェクトであった場合、値として渡されたプロミスです。
静的な Promise.resolve
関数は、解決する Promise
を返します。
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 });
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
がどのように動作するのかはこちらを参照してください。
// 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 });
仕様書 |
---|
{{SpecName('ESDraft', '#sec-promise.resolve', 'Promise.resolve')}} |
{{Compat("javascript.builtins.Promise.resolve")}}