JavaScript—Promise
文章目录
1. Promise
Promise 用于表示异步操作的返回值,它有三种状态:
pending:初始状态,异步操作还未完成;fullfilled:异步操作已被成功执行完毕;rejected:异步操作失败;
可以通过 Promise.then() 向 Promise 添加回调函数,指定在异步操作完成(成功或失败)时要执行的动作:
let task = (resolve, reject) => {
console.log("Start The Task!");
// 在这里指定异步逻辑(此处使用定时器模拟)
setTimeout(() => {
resolve("Success!") // 成功时调用指定的回调函数
}, 250);
};
/*
创建 Promise 时,立即执行 task(resolutionFunc, rejectionFunc);
resolutionFunc 中指定了成功时要执行的操作,
rejectionFunc 中指定了失败时要执行的操作。
*/
let myPromise = new Promise(task);
console.log("...");
/*
成功时,执行指定的回调函数;
失败时要执行的回调可以省略。
*/
myPromise.then((result) => {
console.log("Get Result: ", result);
});Start The Task!
...
Get Result: Success!指定失败时应执行的动作:
let task = (resolve, reject) => {
console.log("Start The Task ...");
setTimeout(() => {
reject("Failed");
}, 250);
};
let myPromise = new Promise(task);
myPromise.then((result) => {
console.log("Get Result: ", result);
}, (err) => {
console.error("Get Error: ", err);
});Start The Task
Get Error: Failed或者通过 Promise.catch() 来指定:
myPromise.catch((err) => {
console.error("Get Error: ", err);
});2. async/await
async 修饰的函数的返回值为 Promise:
async function hello(ok) {
if (ok) {
return "hello, js!";
} else {
throw "not ok!";
}
}
let myPromise = hello(true);
myPromise.then((res) => {
console.log("OK: ", res);
}, (err) => {
console.log("Err: ", err);
});OK: hello, js!await 后面加 Promise,它会挂起当前的执行,直到 Promise 对应的异步操作完成。await 只能在 async 函数中使用。
async function multiply(a, b) {
return a * b;
}
async function main() {
let p1 = multiply(222, 333);
let p2 = multiply(444, 555);
let r1 = await p1;
let r2 = await p2;
return r1 + r2;
}
let myPromise = main();
myPromise.then((res) => {
console.log("OK: ", res);
}, (err) => {
console.log("Err: ", err);
});OK: 320346
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论