javascript 学习笔记3

和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 关键字
复制代码

 

复制代码
实现返回 promises 的 APIs
https://developer.mozilla.org/zh-CN/docs/Learn/JavaScript/Asynchronous/Implementing_a_promise-based_API
const name = document.querySelector('#name'); const delay = document.querySelector('#delay'); const button = document.querySelector('#set-alarm'); const output = document.querySelector('#output'); function alarm(person, delay) { return new Promise((resolve, reject) => { //这两个参数都是函数,通常被称作 resolve 和 reject,如果异步函数成功了,就调用 resolve,如果失败了,就调用 reject if (delay < 0) { throw new Error('Alarm delay must not be negative'); } window.setTimeout(() => { resolve(`Wake up, ${person}!`); }, delay); }); } // 使用这个api button.addEventListener('click', () => { alarm(name.value, delay.value) .then(message => output.textContent = message) .catch(error => output.textContent = `Couldn't set alarm: ${error}`); }); 通过worker实现在单独执行 线程 中运行一些任务: https://developer.mozilla.org/zh-CN/docs/Learn/JavaScript/Asynchronous/Introducing_workers 在单独执行 线程 中运行一些任务 只要 worker 被创建了,woker 脚本就会执行; 使用 worker.postMessage() 向 worker 发送一条消息; 主线程和 worker 不直接共享任何变量,但是可以通过发送消息来进行通信
复制代码

 

posted on   我和你并没有不同  阅读(17)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)
历史上的今天:
2020-03-28 sql 查询相关
2020-03-28 控制你的鼠标和键盘
2020-03-28 TODO
2019-03-28 部署 & virtualen
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示