我们一起深入理解一下Javascript中的asyncawait与promise
async/await 和 Promise 都是 JavaScript 中的异步编程工具。它们的主要区别在于语法和可读性。
Promise 是一种对象,用于表示一个异步操作的最终完成(成功或失败),并提供了一组链式方法(then、catch、finally)来处理这个异步操作的结果。
例如:fetch("https://some-api.com/data") .then(response => response.json()) .then(data => { console.log(data); }) .catch(error => { console.log(error); });
async/await 是语法糖,它可以让我们使用同步的语法来编写异步代码。它依赖于 Promise ,因此在使用 async/await 时,需要先将异步操作封装成 Promise。
例如:async function getData() { const response = await fetch("https://some-api.com/data"); const data = await response.json(); console.log(data); }Promise
Promise 是一种对象,用于表示一个异步操作的最终完成(成功或失败),并提供了一组链式方法(then、catch、finally)来处理这个异步操作的结果。
例如:fetch("https://some-api.com/data") .then(response => response.json()) .then(data => { console.log(data); }) .catch(error => { console.log(error); });
Promise通常包含以下方法:Promise.all(iterable) 方法用于将多个Promise实例包装成一个新的Promise实例。当所有的Promise都成功时,新的Promise实例才会成功,否则它就会失败。 例如:const promise1 = Promise.resolve(3); const promise2 = 42; const promise3 = new Promise((resolve, reject) => { setTimeout(resolve, 100, "foo"); }); Promise.all([promise1, promise2, promise3]).then((values) => { console.log(values); }); // expected output: Array [3, 42, "foo"] Promise.any(iterable) 方法用于将多个Promise实例包装成一个新的Promise实例。只要有一个Promise成功,新的Promise实例就会成功,否则它就会失败。 例如:const promise1 = new Promise((resolve, reject) => { setTimeout(resolve, 1000, "first"); }); const promise2 = new Promise((resolve, reject) => { setTimeout(resolve, 2000, "second"); }); const promise3 = new Promise((resolve, reject) => { setTimeout(resolve, 3000, "third"); }); Promise.any([promise1, promise2, promise3]).then((value) => { console.log(value); }); // expected output: "first" Promise.race(iterable) 方法用于将多个Promise实例包装成一个新的Promise实例。当其中任意一个Promise成功或失败时,新的Promise实例就会成功或失败。 例如:const promise1 = new Promise((resolve, reject) => { setTimeout(resolve, 3000, "first"); }); const promise2 = new Promise((resolve, reject) => { setTimeout(reject, 2000, "second"); }); const promise3 = new Promise((resolve, reject) => { setTimeout(resolve, 1000, "third"); }); Promise.race([promise1, promise2, promise3]).then((value) => { console.log(value); }, (reason) => { console.log(reason); });Promise.allSettled(iterable) 方法用于将多个Promise实例包装成一个新的Promise实例。该Promise在所有给定的Promise都完成后才会完成。这可能是成功或失败。 例如:const promise1 = new Promise((resolve, reject) => { setTimeout(resolve, 1000, "first"); }); const promise2 = new Promise((resolve, reject) => { setTimeout(reject, 2000, "second"); }); const promise3 = new Promise((resolve, reject) => { setTimeout(resolve, 3000, "third"); }); Promise.allSettled([promise1, promise2, promise3]).then(values => { console.log(values); }); // expected output: [{ status: "fulfilled", value: "first" }, { status: "rejected", reason: "second" }, { status: "fulfilled", value: "third" }]async/await
async/await 是语法糖,它可以让我们使用同步的语法来编写异步代码。它依赖于 Promise ,因此在使用 async/await 时,需要先将异步操作封装成 Promise。
例如:async function getData() { const response = await fetch("https://some-api.com/data"); const data = await response.json(); console.log(data); }
async/await 是ES7 引入的对 JavaScript 异步编程的一种改进,它提供了使用同步样式代码异步访问资源的选项,而不会阻塞主线程。使用 async/await 的优点
最重要的优点之一是它具有同步编程风格。让我们来看一个例子:// async/await const getArticlesByAuthorWithAwait = async (authorId) => { const articles = await articleModel.fetchAll(); return articles.filter((b) => b.authorId === authorId); }; // promise const getArticlesByAuthorWithPromise = (authorId) => { return articleModel .fetchAll() .then((articles) => articles.filter((b) => b.authorId === authorId)); };
可以看到,使用 async/await 版本比使用 promise 版本更容易理解。如果忽略 await 关键字,代码看起来就像其他同步语言,如 Python。 另外, async/await 在主流浏览器中有原生支持。
需要注意的是,在使用 async/await 时,需要成对出现。例如,在函数中使用 await,则必须将函数定义为 async。使用 async/await 可能会产生一些误导和陷阱
async/await虽好,但是使用不当可能会产生一些问题。await 并不会等待上一个异步操作完成。它只是让 JavaScript 引擎知道在这个点上应该等待,并且在异步操作完成后继续执行代码。 例如:const getData = async () => { console.log("Start getting data"); const data1 = await fetchData1(); console.log("Data 1 received"); const data2 = await fetchData2(); console.log("Data 2 received"); return { data1, data2 }; }; getData(); console.log("End of script");
这段代码会先输出"Start getting data",然后"End of script",最后再输出"Data 1 received"和"Data 2 received"await 不能在普通函数中使用。它只能在 async 函数中使用。 例如:const getData = () => { const data = await fetchData(); // TypeError: await is only valid in async function return data; };await 只能用于 Promise 对象。如果传入的不是一个Promise对象,会立即resolve。 例如:const data = await 42; console.log(data); // 42await 后面的代码会被封装在 try/catch 中,如果出错,会产生reject状态。 例如:const getData = async () => { try { const data = await fetchData(); return data; } catch (error) { console.error(error); } };
async/await 是一种具有可读性和错误处理能力的新型异步编程方式,可以让我们更容易理解和维护异步代码。在使用 async/await 时,需要注意它依然是异步代码,不能直接和同步代码一起工作。需要使用 promise 对象或回调函数来将异步代码的结果传递给同步代码。在使用 async/await 时还要注意使用 try/catch 来处理可能出现的错误。