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