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

Promise - JavaScript | MDN

MDN Web Docs

View in English Always switch to English

Promise

Promise Promise Promise Promise

Promise

createAudioFileAsync()

createAudioFileAsync()

js
// 
function successCallback(result) {
  console.log("" + result);
}

// 
function failureCallback(error) {
  console.log("" + error);
}

createAudioFileAsync(audioSettings, successCallback, failureCallback);

createAudioFileAsync() Promise

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

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

Promise Promise Promise API Promise

then() Promise

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

promisepromise2 doSomething() successCallback failureCallback Promise promise2 promise successCallback failureCallback

Promise

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

API Promise

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 Promise Promise Promise then Promise Promise undefined Promise Promise

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

fetch Promise

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

Promise Promise 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  [] fetch 
  });

Promise 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 await

async/await promisedoSomething() promise async/await async/await await

async/await Promise await await

3 failureCallback Promise

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

Promise onRejected .catch()

js
try {
  let result = syncDoSomething();
  let newResult = syncDoSomethingElse(result);
  let 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);
  }
}

listOfIngredients Promise then() Promise Promise

catch catch

js
doSomethingCritical()
  .then((result) =>
    doSomethingOptional()
      .then((optionalResult) => doSomethingExtraNice(optionalResult))
      .catch((e) => {}),
  ) // 
  .then(() => moreCriticalStuff())
  .catch((e) => console.log(`${e.message}`));

( )

catch doSomethingOptional() doSomethingExtraNice() moreCriticalStuff() doSomethingCritical() catch 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(`${e.message}`);
  }
}

then

Catch

catch

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

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

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



then() throw

async/await

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

Promise

Promise Web Promise window web worker Worker worker

unhandledrejection

promise

rejectionhandled

promise unhandledrejection

PromiseRejectionEvent promise Promise reason Promise

Promise Promise

Node.js Node.js unhandledRejection

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

Node.js process.on() preventDefault()

process.on Promise Promise

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

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

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

Promise Promise JavaScript

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

reduce Promise

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 Promise Promise Promise

API Promise

Promise Promise API

Promise API setTimeout()

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

Promise saySomething setTimeout()

setTimeout() Promise

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

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

Promise executorresolvereject Promise setTimeout() Promise()

API API

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

Zalgo API API API

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

Promise API Promise API

then() Promise resolved

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

then() JavaScript

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

vs.

Promise setTimeout()

js
const promise = new Promise((resolve, reject) => {
  console.log("Promise ");
  resolve();
}).then((result) => {
  console.log("Promise .then");
});

setTimeout(() => {
  console.log("Promise", promise);
}, 0);

console.log("Promise", promise);

Promise 
PromisePromise {<pending>}
Promise .then
PromisePromise {<fulfilled>}

Javascript

Promise

Promise Promise Promise

queueMicrotask()


Web Proxy Viewer  |  New URL  |  Original Page