| [ Web Proxy ] |
| Viewing: https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Promise | [Back] [Original] |
Get to know MDN better
(Promise)
Promise
(fulfilled) () (rejected)
then
(settled)
[then/catch "on fulfillment" then() then() 2 catch() ]
(resolved) States and fates "States and fates"
new Promise((resolveOuter) => {
resolveOuter(
new Promise((resolveInner) => {
setTimeout(resolveInner, 1000);
}),
);
});
resolveOuter 1
:
Scheme JavaScript f = () => expression f()
Promise AbortController
then(), catch(), finally() then() 2 1 2 catch() finally() then() catch() then()
const myPromise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("foo");
}, 300);
});
myPromise
.then(handleFulfilledA, handleRejectedA)
.then(handleFulfilledB, handleRejectedB)
.then(handleFulfilledC, handleRejectedC);
then then then 2
myPromise handleRejectedA handleRejectedA then catch()
myPromise
.then(handleFulfilledA)
.then(handleFulfilledB)
.then(handleFulfilledC)
.catch(handleRejectedAny);
myPromise
.then((value) => `${value} and bar`)
.then((value) => `${value} and bar again`)
.then((value) => `${value} and again`)
.then((value) => `${value} and again`)
.then((value) => {
console.log(value);
})
.catch((err) => {
console.error(err);
});
: 1
JavaScript JavaScript Promise() then API
promiseA handleFulfilled1 handleFulfilled2 handleFulfilled1
const promiseA = new Promise(myExecutorFunc);
const promiseB = promiseA.then(handleFulfilled1, handleRejected1);
const promiseC = promiseA.then(handleFulfilled2, handleRejected2);
1
const promiseA = new Promise((resolve, reject) => {
resolve(777);
});
// "promiseA"
promiseA.then((val) => console.log("asynchronous logging has val:", val));
console.log("immediate logging");
//
// immediate logging
// asynchronous logging has val: 777
JavaScript Thenable Thenable .then() 2 1 1 Thenable
Thenable Promise.resolve Thenable
// Promises/A+ thenable onFulfilled
//
const thenable = {
then(onFulfilled, onRejected) {
onFulfilled({
// Thenable Thenable
then(onFulfilled, onRejected) {
onFulfilled(42);
},
});
},
};
Promise.resolve(thenable); // 42
then() onFulfilled onRejected Promises/A+ () thenable Bluebird()
Thenable Promise Promise() executor resolve reject resolve Promise.resolve()
2 Promise.allKeyed() Promise.allSettledKeyed() Promise.all() Promise.allSettled()
then() Promise.race()
const pendingPromise = new Promise(() => {});
for (let i = 0; i < 1000; i++) {
await Promise.race([Promise.resolve(0), pendingPromise]);
}
// pendingPromise 1000
//
Promise() Promise
Promise.all() Promise
Promise.allKeyed() Promise.all()
Promise.allSettled() Promise
Promise.allSettledKeyed() Promise.allSettled()
Promise.any() Promise AggregateError
Promise.race() Promise
Promise.reject() Promise
Promise.resolve() Promise Thenable then Thenable
Promise.try() Promise
Promise.withResolvers()Promise() 2 Promise 2
Promise.prototype Promise
Promise.prototype.catch()
Promise.prototype.finally()Promise.prototype.then() onFulfilled onRejected
setTimeout(...)
XHR HTML API
const myFirstPromise = new Promise((resolve, reject) => {
// resolve(...)
// reject(...)
setTimeout(() => {
resolve("!"); //
}, 250);
});
myFirstPromise.then((successMessage) => {
// successMessage resolve(...)
//
console.log(`Yay! ${successMessage}`);
});
.then() () .catch() .finally() new Promise() API ()
tetheredGetNumber() reject() promiseGetWord() API
troubleWithGetNumber() throw .then() throw .then() onRejected catch() onRejected
Node.js threshold
// "threshold"
const THRESHOLD_A = 8; // 0
function tetheredGetNumber(resolve, reject) {
setTimeout(() => {
const randomInt = Date.now();
const value = randomInt % 10;
if (value < THRESHOLD_A) {
resolve(value);
} else {
reject(new RangeError(`: ${value}`));
}
}, 500);
}
function determineParity(value) {
const isOdd = value % 2 === 1;
return { value, isOdd };
}
function troubleWithGetNumber(reason) {
const err = new Error("", { cause: reason });
console.error(err);
throw err;
}
function promiseGetWord(parityInfo) {
return new Promise((resolve, reject) => {
const { value, isOdd } = parityInfo;
if (value >= THRESHOLD_A - 1) {
reject(new RangeError(`: ${value}`));
} else {
parityInfo.wordEvenOdd = isOdd ? "odd" : "even";
resolve(parityInfo);
}
});
}
new Promise(tetheredGetNumber)
.then(determineParity, troubleWithGetNumber)
.then(promiseGetWord)
.then((info) => {
console.log(`Got: ${info.value}, ${info.wordEvenOdd}`);
return info;
})
.catch((reason) => {
if (reason.cause) {
console.error("");
} else {
console.error(`promiseGetWord() : ${reason}`);
}
})
.finally((info) => console.log(""));
Promise testPromise() <button> setTimeout() 1 3 Promise()
<button id="make-promise"></button>
<div id="log"></div>
"use strict";
let promiseCount = 0;
function testPromise() {
const thisPromiseCount = ++promiseCount;
const log = document.getElementById("log");
//
log.insertAdjacentHTML("beforeend", `${thisPromiseCount}) <br>`);
// 1 3
const p1 = new Promise((resolve, reject) => {
//
log.insertAdjacentHTML(
"beforeend",
`${thisPromiseCount}) Promise <br>`,
);
//
setTimeout(
() => {
//
resolve(thisPromiseCount);
},
Math.random() * 2000 + 1000,
);
});
// then()
// catch()
p1.then((val) => {
// Log the fulfillment value
log.insertAdjacentHTML("beforeend", `${val}) Promise <br>`);
}).catch((reason) => {
// Log the rejection reason
console.log(` (${reason}) `);
});
//
log.insertAdjacentHTML("beforeend", `${thisPromiseCount}) Promise <br>`);
}
const btn = document.getElementById("make-promise");
btn.addEventListener("click", testPromise);
Promise XMLHttpRequest
Promise XHR
<h1></h1>
function imgLoad(url) {
// Promise()
// 2 resolve reject
return new Promise((resolve, reject) => {
// XHR
const request = new XMLHttpRequest();
request.open("GET", url);
request.responseType = "blob";
//
request.onload = () => {
if (request.status === 200) {
//
resolve(request.response);
} else {
//
reject(
Error(
`: + ${request.statusText}`,
),
);
}
};
//
request.onerror = () => reject(new Error(""));
//
request.send();
});
}
//
const body = document.querySelector("body");
const myImage = new Image();
const imgUrl =
"https://mdn.github.io/shared-assets/images/examples/round-balloon.png";
// URL then()
// 2
imgLoad(imgUrl).then(
(response) => {
// resolve()
// request.response
const imageURL = URL.createObjectURL(response);
myImage.src = imageURL;
body.appendChild(myImage);
},
(error) => {
// 2
// reject()
console.log(error);
},
);
(settings object) JavaScript HTML
(realm) JavaScript Array Error (incumbent settings object)
<iframe> Web API
<!doctype html>
<iframe></iframe>
<!-- -->
<script>
//
const bound = frames[0].postMessage.bind(frames[0], "some data", "*");
// bound
//
setTimeout(bound);
//
//
</script>
<!doctype html>
<iframe></iframe>
<!-- -->
<script>
//
const bound = frames[0].postMessage.bind(frames[0], "some data", "*");
// bound
//
Promise.resolve(undefined).then(bound);
//
//
</script>
<iframe> post
<!-- y.html -->
<!doctype html>
<iframe src="x.html"></iframe>
<script>
const bound = frames[0].postMessage.bind(frames[0], "some data", "*");
Promise.resolve(undefined).then(bound);
</script>
<!-- x.html -->
<!doctype html>
<script>
window.addEventListener("message", (event) => {
document.querySelector("#text").textContent = "hello";
//
console.log(event);
});
</script>
<iframe>
: Firefox Chrome Safari
| ECMAScript 2027 LanguageSpecification # sec-promise-objects |
Promise (core-js)| Web Proxy Viewer | New URL | Original Page |