[ Web Proxy ]
URL:
Viewing: https://developer.mozilla.org/ko/docs/Web/JavaScript/Guide/Using_promises#composition [Back]  [Original]

Using promises - JavaScript | MDN

This page was translated from English by the community. Learn more and join the MDN Web Docs community.

View in English Always switch to English

Using promises

Promise . promise promise promise .

promise , .

createAudioFileAsync() . , . , .

createAudioFileAsync() .

js
function successCallback(result) {
  console.log("Audio file ready at URL: " + result);
}

function failureCallback(error) {
  console.log("Error generating audio file: " + error);
}

createAudioFileAsync(audioSettings, successCallback, failureCallback);

Promise .

createAudioFileAsync() Promise , .

js
createAudioFileAsync(audioSettings).then(successCallback, failureCallback);

:

js
const promise = createAudioFileAsync(audioSettings);
promise.then(successCallback, failureCallback);

. . .

In this article

Guarantees

, Promise .

Promise chaining.

Chaining

. . promise chain .

then() promise . promise promise.

js
const promise = doSomething();
const promise2 = promise.then(successCallback, failureCallback);

js
const promise2 = doSomething().then(successCallback, failureCallback);

promise doSomething() successCallback or failureCallback . successCallback or failureCallback promise . promise2 successCallback failureCallback promise .

, promise .

' ' .

js
doSomething(function (result) {
  doSomethingElse(
    result,
    function (newResult) {
      doThirdThing(
        newResult,
        function (finalResult) {
          console.log("Got the final result: " + finalResult);
        },
        failureCallback,
      );
    },
    failureCallback,
  );
}, failureCallback);

, promise promise chain :

js
doSomething()
  .then(function (result) {
    return doSomethingElse(result);
  })
  .then(function (newResult) {
    return doThirdThing(newResult);
  })
  .then(function (finalResult) {
    console.log("Got the final result: " + finalResult);
  })
  .catch(failureCallback);

then (optional). catch(failureCallback) then(null, failureCallback) . .

js
doSomething()
  .then((result) => doSomethingElse(result))
  .then((newResult) => doThirdThing(newResult))
  .then((finalResult) => {
    console.log(`Got the final result: ${finalResult}`);
  })
  .catch(failureCallback);

: , promise . ( () => x () => {return x;} .)

Chaining after a catch

chain . ( : catch) :

js
new Promise((resolve, reject) => {
  console.log("Initial");

  resolve();
})
  .then(() => {
    throw new Error("Something failed");

    console.log("Do this");
  })
  .catch(() => {
    console.log("Do that");
  })
  .then(() => {
    console.log("Do this, whatever happened before");
  });

.

    Initial
    Do that
    Do this, whatever happened before

: "Do this" . "Something failed" rejection .

Error propagation

' ' failureCallback 3 . promise chain .

js
doSomething()
  .then((result) => doSomethingElse(result))
  .then((newResult) => doThirdThing(newResult))
  .then((finalResult) => console.log(`Got the final result: ${finalResult}`))
  .catch(failureCallback);

promise chain chain catch . .

js
try {
  const result = syncDoSomething();
  const newResult = syncDoSomethingElse(result);
  const finalResult = syncDoThirdThing(newResult);
  console.log(`Got the final result: ${finalResult}`);
} catch (error) {
  failureCallback(error);
}

ECMAScript 2017 async/await (Syntactic sugar) .

js
async function foo() {
  try {
    const result = await doSomething();
    const newResult = await doSomethingElse(result);
    const finalResult = await doThirdThing(newResult);
    console.log(`Got the final result: ${finalResult}`);
  } catch (error) {
    failureCallback(error);
  }
}

promise . doSomething() . .

Promise , . .

Promise rejection events

Promise reject .(, window, , Worker, .) .

rejectionhandled

executor reject reject promise reject .

unhandledrejection

promise reject reject .

(PromiseRejectionEvent ) promise reason . promise reject promise , reason promise reject .

(fallback) , . (global) , (source) .

: Node.js , reject . . . . unhandledrejection() .

js
window.addEventListener(
  "unhandledrejection",
  (event) => {
    /* You might start here by adding code to examine the
     promise specified by event.promise and the reason in
     event.reason */

    event.preventDefault();
  },
  false,
);

preventDefault() reject JavaScript . , NodeJS .

, , reject .

API Promise

Promise . API .

promise , API success / failure . setTimeout () .

js
setTimeout(() => saySomething("10 seconds passed"), 10000);

Promise . saySomething() . setTimeout .

setTimeout Promise . .

js
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

wait(10000)
  .then(() => saySomething("10 seconds"))
  .catch(failureCallback);

promise constructor promise reject . setTimeout() fail error reject .

Composition

Promise.resolve() Promise.reject() resolve reject promise . .

Promise.all() Promise.race() .

.

js
Promise.all([func1(), func2(), func3()]).then(([result1, result2, result3]) => {
  /* use result1, result2 and result3 */
});

JavaScript .

js
[func1, func2, func3]
  .reduce((p, f) => p.then(f), Promise.resolve())
  .then((result3) => {
    /* use result3 */
  });

, promise . Promise.resolve().then(func1).then(func2).then(func3);

, .

js
const applyAsync = (acc, val) => acc.then(val);
const composeAsync =
  (...funcs) =>
  (x) =>
    funcs.reduce(applyAsync, Promise.resolve(x));

composeAsync() composition .

js
const transformData = composeAsync(func1, func2, func3);
const result3 = transformData(data);

ECMAScript 2017 async / await .

js
let result;
for (const f of [func1, func2, func3]) {
  result = await f(result);
}
/* use last result (i.e. result3) */

Timing

( . , .. ..) then() already-resolved promise .

js
Promise.resolve().then(() => console.log(2));
console.log(1); // 1, 2

. , , .

js
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

wait().then(() => console.log(4));
Promise.resolve()
  .then(() => console.log(2))
  .then(() => console.log(3));
console.log(1); // 1, 2, 3, 4

Nesting

promise . . common mistakes .

catch . , catch . .

js
doSomethingCritical()
  .then((result) =>
    doSomethingOptional(result)
      .then((optionalResult) => doSomethingExtraNice(optionalResult))
      .catch((e) => {}),
  ) // Ignore if optional stuff fails; proceed.
  .then(() => moreCriticalStuff())
  .catch((e) => console.log("Critical failure: " + e.message));

( ) .

inner neutralizing catch doSomethingOptional() doSomethingExtraNice() catch moreCriticalStuff() . doSomethingCritical() () catch .

Common mistakes

promise chains . .

js
// Bad example! Spot 3 mistakes!

doSomething()
  .then(function (result) {
    doSomethingElse(result) // Forgot to return promise from inner chain + unnecessary nesting
      .then((newResult) => doThirdThing(newResult));
  })
  .then(() => doFourthThing());
// Forgot to terminate chain with a catch!

. promise . . , doFourthThing() doSomethingElse() doThirdThing() . .

. , . promise constructor anti-pattern. promise .

catch . promise promise rejection .

promise , promise .

js
doSomething()
  .then(function (result) {
    return doSomethingElse(result);
  })
  .then((newResult) => doThirdThing(newResult))
  .then(() => doFourthThing())
  .catch((error) => console.log(error));

() => x () => { return x; } .

.

async/await . await .

promise

promise (: ) promise promise .

, queueMicrotask() .

See also


Web Proxy Viewer  |  New URL  |  Original Page