| [ Web Proxy ] |
| Viewing: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Guide/Using_promises | [Back] [Original] |
Get to know MDN better
Promise Promise Promise Promise
Promise
createAudioFileAsync()
createAudioFileAsync()
//
function successCallback(result) {
console.log("" + result);
}
//
function failureCallback(error) {
console.log("" + error);
}
createAudioFileAsync(audioSettings, successCallback, failureCallback);
createAudioFileAsync() Promise
createAudioFileAsync(audioSettings).then(successCallback, failureCallback);
doSomething(function (result) {
doSomethingElse(result, function (newResult) {
doThirdThing(newResult, function (finalResult) {
console.log(`${finalResult}`);
}, failureCallback);
}, failureCallback);
}, failureCallback);
Promise Promise Promise API Promise
then() Promise
const promise = doSomething();
const promise2 = promise.then(successCallback, failureCallback);
promisepromise2 doSomething() successCallback failureCallback Promise promise2 promise successCallback failureCallback
Promise
function doSomething() {
return new Promise((resolve) => {
setTimeout(() => {
// Promise
console.log("");
// promise
resolve("https://example.com/");
}, 200);
});
}
Promise 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 Promise Promise Promise then Promise Promise undefined Promise Promise
doSomething()
.then((url) => {
// fetch(url) `return`
fetch(url);
})
.then((result) => {
// result undefined
// fetch()
});
fetch Promise
doSomething()
.then((url) => {
// `return`
return fetch(url);
})
.then((result) => {
// result Response
});
Promise Promise 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 [] fetch
});
Promise 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 await
async/await promisedoSomething() promise async/await async/await await
async/await Promise await await
3 failureCallback Promise
doSomething()
.then((result) => doSomethingElse(result))
.then((newResult) => doThirdThing(newResult))
.then((finalResult) => console.log(`${finalResult}`))
.catch(failureCallback);
Promise onRejected .catch()
try {
let result = syncDoSomething();
let newResult = syncDoSomethingElse(result);
let finalResult = syncDoThirdThing(newResult);
console.log(`${finalResult}`);
} catch (error) {
failureCallback(error);
}
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
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
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
new Promise((resolve, reject) => {
console.log("");
resolve();
})
.then(() => {
throw new Error("");
console.log("");
})
.catch(() => {
console.log("");
})
.then(() => {
console.log("");
});
then() throw
async/await
async function main() {
try {
await doSomething();
throw new Error("");
console.log("");
} catch (e) {
console.error("");
}
console.log("");
}
Promise Web Promise window web worker Worker worker
unhandledrejectionpromise
rejectionhandled promise unhandledrejection
PromiseRejectionEvent promise Promise reason Promise
Promise Promise
Node.js Node.js unhandledRejection
process.on("unhandledRejection", (reason, promise) => {
/* promise reason */
});
Node.js process.on() preventDefault()
process.on Promise Promise
Promise.all()Promise.allSettled()Promise.any() Promise.race()
Promise.all([func1(), func2(), func3()]).then(([result1, result2, result3]) => {
/* result1result2 result3 */
});
Promise Promise.all() PromisePromise.allSettled() Promise
Promise Promise JavaScript
[func1, func2, func3]
.reduce((p, f) => p.then(f), Promise.resolve())
.then((result3) => {
/* result3 */
});
reduce Promise
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 Promise Promise Promise
Promise Promise API
Promise API setTimeout()
setTimeout(() => saySomething("10 "), 10 * 1000);
Promise saySomething setTimeout()
setTimeout() Promise
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
wait(10 * 1000)
.then(() => saySomething("10 "))
.catch(failureCallback);
Promise executorresolvereject Promise setTimeout() Promise()
API API
function doSomething(callback) {
if (Math.random() > 0.5) {
callback();
} else {
setTimeout(() => callback(), 1000);
}
}
Zalgo API API API
let value = 1;
doSomething(() => {
value = 2;
});
console.log(value); // 1 2
then() Promise resolved
Promise.resolve().then(() => console.log(2));
console.log(1); // 1, 2
then() JavaScript
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
Promise setTimeout()
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>}
Promise Promise Promise
Promiseasync functionawait| Web Proxy Viewer | New URL | Original Page |