| [ Web Proxy ] |
| Viewing: https://developer.mozilla.org/ja/docs/Web/JavaScript/Guide/Using_promises | [Back] [Original] |
Get to know MDN better
(Promise)
createAudioFileAsync() 2
createAudioFileAsync()
function successCallback(result) {
console.log(`Audio file ready at URL: ${result}`);
}
function failureCallback(error) {
console.error(`Error generating audio file: ${error}`);
}
createAudioFileAsync(audioSettings, successCallback, failureCallback);
createAudioFileAsync()
createAudioFileAsync(audioSettings).then(successCallback, failureCallback);
doSomething(function (result) {
doSomethingElse(result, function (newResult) {
doThirdThing(newResult, function (finalResult) {
console.log(`: ${finalResult}`);
}, failureCallback);
}, failureCallback);
}, failureCallback);
API
then()
const promise = doSomething();
const promise2 = promise.then(successCallback, failureCallback);
2 (promise2) doSomething() successCallback failureCallback promise2 successCallback failureCallback
:
function doSomething() {
return new Promise((resolve) => {
setTimeout(() => {
//
console.log("");
//
resolve("https://example.com/");
}, 200);
});
}
then catch(failureCallback) then(null, failureCallback)
doSomething()
.then(function (result) {
return doSomethingElse(result);
})
.then(function (newResult) {
return doThirdThing(newResult);
})
.then(function (finalResult) {
console.log(`: ${finalResult}`);
})
.catch(failureCallback);
doSomething()
.then((result) => doSomethingElse(result))
.then((newResult) => doThirdThing(newResult))
.then((finalResult) => {
console.log(`: ${finalResult}`);
})
.catch(failureCallback);
doSomethingElse doThirdThing undefined then (floating)
doSomething()
.then((url) => {
// fetch(url) return
fetch(url);
})
.then((result) => {
// fetch()
});
fetch
doSomething()
.then((url) => {
// `return`
return fetch(url);
})
.then((result) => {
// Response
});
then
const listOfIngredients = [];
doSomething()
.then((url) => {
// fetch(url) return
fetch(url)
.then((res) => res.json())
.then((data) => {
listOfIngredients.push(data);
});
})
.then(() => {
console.log(listOfIngredients);
// listOfIngredients []
});
then
const listOfIngredients = [];
doSomething()
.then((url) => {
// fetch `return`
return fetch(url)
.then((res) => res.json())
.then((data) => {
listOfIngredients.push(data);
});
})
.then(() => {
console.log(listOfIngredients);
// listOfIngredients fetch
});
doSomething()
.then((url) => fetch(url))
.then((res) => res.json())
.then((data) => {
listOfIngredients.push(data);
})
.then(() => {
console.log(listOfIngredients);
});
async/await async/await
async function logIngredients() {
const url = await doSomething();
const res = await fetch(url);
const data = await res.json();
listOfIngredients.push(data);
console.log(listOfIngredients);
}
await 1 await
async/await doSomething() async/await async/await await
:
async/await 1 await await
failureCallback 3 1
doSomething()
.then((result) => doSomethingElse(result))
.then((newResult) => doThirdThing(newResult))
.then((finalResult) => console.log(`: ${finalResult}`))
.catch(failureCallback);
.catch() onRejected
try {
const result = syncDoSomething();
const newResult = syncDoSomethingElse(result);
const finalResult = syncDoThirdThing(newResult);
console.log(`: ${finalResult}`);
} catch (error) {
failureCallback(error);
}
async/await
async function foo() {
try {
const result = await doSomething();
const newResult = await doSomethingElse(result);
const finalResult = await doThirdThing(newResult);
console.log(`: ${finalResult}`);
} catch (error) {
failureCallback(error);
}
}
catch() async/await try/catch
listOfIngredients then() 2
catch catch
doSomethingCritical()
.then((result) =>
doSomethingOptional(result)
.then((optionalResult) => doSomethingExtraNice(optionalResult))
.catch((e) => {}),
) //
.then(() => moreCriticalStuff())
.catch((e) => console.error(`Critical failure: ${e.message}`));
( )
catch doSomethingOptional() doSomethingExtraNice() moreCriticalStuff() doSomethingCritical() () catch
async/await
async function main() {
try {
const result = await doSomethingCritical();
try {
const optionalResult = await doSomethingOptional(result);
await doSomethingExtraNice(optionalResult);
} catch (e) {
//
}
await moreCriticalStuff();
} catch (e) {
console.error(`Critical failure: ${e.message}`);
}
}
:
then
catch
doSomething()
.then(() => {
throw new Error("");
console.log("");
})
.catch(() => {
console.error("");
})
.then(() => {
console.log("");
});
:
async/await
async function main() {
try {
await doSomething();
throw new Error("");
console.log("");
} catch (e) {
console.error("");
}
console.log("");
}
PromiseRejectionEvent promise reason
Node.js Node.js unhandledRejection
process.on("unhandledRejection", (reason, promise) => {
// "promise" "reason"
});
Node.js () process.on() preventDefault()
process.on
4 Promise.all()Promise.allSettled()Promise.any()Promise.race()
Promise.all([func1(), func2(), func3()]).then(([result1, result2, result3]) => {
// result1, result2, result3
});
Promise.all() Promise.all() Promise.allSettled()
JavaScript
[func1, func2, func3]
.reduce((p, f) => p.then(f), Promise.resolve())
.then((result3) => {
// result3
});
Promise.resolve()
.then(func1)
.then(func2)
.then(func3)
.then((result3) => {
/* result3 */
});
const applyAsync = (acc, val) => acc.then(val);
const composeAsync =
(...funcs) =>
(x) =>
funcs.reduce(applyAsync, Promise.resolve(x));
composeAsync()
const transformData = composeAsync(func1, func2, func3);
const result3 = transformData(data);
async/await
let result;
for (const f of [func1, func2, func3]) {
result = await f(result);
}
/* ( result3) */
Promise AbortController
Promise 1 API
API / setTimeout()
setTimeout(() => saySomething("10 seconds passed"), 10 * 1000);
saySomething() setTimeout()
setTimeout()
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
wait(10 * 1000)
.then(() => saySomething("10 seconds"))
.catch(failureCallback);
setTimeout() Promise()
API API
function doSomething(callback) {
if (Math.random() > 0.5) {
callback();
} else {
setTimeout(() => callback(), 1000);
}
}
API Designing APIs for Asynchrony API
let value = 1;
doSomething(() => {
value = 2;
});
console.log(value); // 1 or 2?
Promise.resolve().then(() => console.log(2));
console.log(1);
// Logs: 1, 2
JavaScript
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
wait(0).then(() => console.log(4));
Promise.resolve()
.then(() => console.log(2))
.then(() => console.log(3));
console.log(1); // 1, 2, 3, 4
const promise = new Promise((resolve, reject) => {
console.log("Promise callback");
resolve();
}).then((result) => {
console.log("Promise callback (.then)");
});
setTimeout(() => {
console.log("event-loop cycle: Promise (fulfilled)", promise);
}, 0);
console.log("Promise (pending)", promise);
Promise callback
Promise (pending) Promise {<pending>}
Promise callback (.then)
event-loop cycle: Promise (fulfilled) Promise {<fulfilled>}
Promiseasync functionawait| Web Proxy Viewer | New URL | Original Page |