和let一样,通过 const 定义的变量不会被提升到顶端。const 变量不能在声明之前使用。
回调函数曾经是 JavaScript 中实现异步函数的主要方式。
=>的使用: function doStep1(init, callback) { const result = init + 1; callback(result); } function doStep2(init, callback) { const result = init + 2; callback(result); } function doStep3(init, callback) { const result = init + 3; callback(result); } function doOperation() { doStep1(0, result1 => { doStep2(result1, result2 => { doStep3(result2, result3 => { console.log(`结果:${result3}`); }); }); }); } doOperation();
fetch() API,一个现代的、基于 Promise 的、用于替代 XMLHttpRequest 的方法 const fetchPromise = fetch('https://mdn.github.io/learning-area/javascript/apis/fetching-data/can-store/products.json'); fetchPromise .then( response => { if (!response.ok) { throw new Error(`HTTP error: ${response.status}`); // 抛出异常 } return response.json(); // json() 也是异步的 }) .then( json => { console.log(json[0].name); }); 将处理程序传递到Promise 对象的 then() 方法中, Promise 对象还提供了一个 catch() 方法来支持错误处理。这很像 then()。 当异步操作成功时,传递给 then() 的处理函数被调用,而当异步操作失败时,传递给 catch() 的处理函数被调用。 如果将 catch() 添加到 Promise 链的末尾,它就可以在任何异步函数失败时被调用。 有时你需要所有的 Promise 都得到实现,但它们并不相互依赖。在这种情况下,将它们一起启动然后在它们全部被兑现后得到通知会更有效率。这里需要 Promise.all() 方法。它接收一个 Promise 数组,并返回一个单一的 Promise。 由Promise.all()返回的 Promise: 当且仅当数组中所有的 Promise 都被兑现时,才会通知 then() 处理函数并提供一个包含所有响应的数组,数组中响应的顺序与被传入 all() 的 Promise 的顺序相同。 会被拒绝——如果数组中有任何一个 Promise 被拒绝。此时,catch() 处理函数被调用,并提供被拒绝的 Promise 所抛出的错误。 const fetchPromise1 = fetch('https://mdn.github.io/learning-area/javascript/apis/fetching-data/can-store/products.json'); const fetchPromise2 = fetch('https://mdn.github.io/learning-area/javascript/apis/fetching-data/can-store/not-found'); const fetchPromise3 = fetch('https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json'); Promise.all([fetchPromise1, fetchPromise2, fetchPromise3]) .then( responses => { for (const response of responses) { console.log(`${response.url}:${response.status}`); } }) .catch( error => { console.error(`获取失败:${error}`) }); 有时,你可能需要等待一组 Promise 中的某一个 Promise 的执行,而不关心是哪一个。在这种情况下,你需要 Promise.any()。这就像 Promise.all(),
不过在 Promise 数组中的任何一个被兑现时它就会被兑现,如果所有的 Promise 都被拒绝,它也会被拒绝。 Promise的具体使用方法详见: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise 在一个函数的开头添加 async,就可以使其成为一个异步函数。在异步函数中,你可以在调用一个返回 Promise 的函数之前使用 await 关键字。