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

- JavaScript | MDN

MDN Web Docs

View in English Always switch to English

(Promise)

createAudioFileAsync() 2

createAudioFileAsync()

js
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()

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

2

js
doSomething(function (result) {
  doSomethingElse(result, function (newResult) {
    doThirdThing(newResult, function (finalResult) {
      console.log(`: ${finalResult}`);
    }, failureCallback);
  }, failureCallback);
}, failureCallback);

API

then()

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

2 (promise2) doSomething() successCallback failureCallback promise2 successCallback failureCallback

:

js
function doSomething() {
  return new Promise((resolve) => {
    setTimeout(() => {
      // 
      console.log("");
      // 
      resolve("https://example.com/");
    }, 200);
  });
}

API Promise

then catch(failureCallback) then(null, failureCallback)

js
doSomething()
  .then(function (result) {
    return doSomethingElse(result);
  })
  .then(function (newResult) {
    return doThirdThing(newResult);
  })
  .then(function (finalResult) {
    console.log(`: ${finalResult}`);
  })
  .catch(failureCallback);

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

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

doSomethingElse doThirdThing undefined then (floating)

js
doSomething()
  .then((url) => {
    // fetch(url)  return 
    fetch(url);
  })
  .then((result) => {
    //  fetch() 
  });

fetch

js
doSomething()
  .then((url) => {
    // `return` 
    return fetch(url);
  })
  .then((result) => {
    //  Response 
  });

then

js
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

js
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 
  });

js
doSomething()
  .then((url) => fetch(url))
  .then((res) => res.json())
  .then((data) => {
    listOfIngredients.push(data);
  })
  .then(() => {
    console.log(listOfIngredients);
  });

async/await async/await

js
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

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

.catch() onRejected

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

async/await

js
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

js
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

js
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

catch

js
doSomething()
  .then(() => {
    throw new Error("");

    console.log("");
  })
  .catch(() => {
    console.error("");
  })
  .then(() => {
    console.log("");
  });


:

async/await

js
async function main() {
  try {
    await doSomething();
    throw new Error("");
    console.log("");
  } catch (e) {
    console.error("");
  }
  console.log("");
}

2 window Worker 2

unhandledrejection

rejectionhandled

reject

PromiseRejectionEvent promise reason

Node.js Node.js unhandledRejection

js
process.on("unhandledRejection", (reason, promise) => {
  // "promise"  "reason" 
});

Node.js () process.on() preventDefault()

process.on

4 Promise.all()Promise.allSettled()Promise.any()Promise.race()

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

Promise.all() Promise.all() Promise.allSettled()

JavaScript

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

js
Promise.resolve()
  .then(func1)
  .then(func2)
  .then(func3)
  .then((result3) => {
    /* result3  */
  });

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

composeAsync()

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

async/await

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

Promise AbortController

API Promise

Promise 1 API

API / setTimeout()

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

saySomething() setTimeout()

setTimeout()

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

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

setTimeout() Promise()

API API

js
function doSomething(callback) {
  if (Math.random() > 0.5) {
    callback();
  } else {
    setTimeout(() => callback(), 1000);
  }
}

API Designing APIs for Asynchrony API

js
let value = 1;
doSomething(() => {
  value = 2;
});
console.log(value); // 1 or 2?

API API API

then()

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

JavaScript

js
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

setTimeout()

js
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>}

queueMicrotask()


Web Proxy Viewer  |  New URL  |  Original Page