🌮 从「callback 地狱」到「Promise 外卖」的进化史

还记得 JS 远古时代吗?回调函数像缠在键盘上的耳机线 —— 你想获取用户数据?得写三层嵌套回调,最后自己都分不清successerror谁先执行。这就好比你让朋友帮忙买奶茶:

// 回调地狱版买奶茶
buyMilkTea('芋泥波波', function(tea) {
  addPearl(tea, function(withPearl) {
    addSugar(withPearl, function(sweetened) {
      console.log('终于喝到了!', sweetened);
    }, function(error) {
      console.log('糖没了!', error);
    });
  }, function(error) {
    console.log('珍珠卖完了!', error);
  });
}, function(error) {
  console.log('奶茶店关门了!', error);
});

ES6 的Promise来了之后,代码瞬间变优雅 —— 就像你用外卖 App 点奶茶,不用一直打电话催,该干嘛干嘛,奶茶做好了 App 会通知你:

// Promise版买奶茶(画饼充饥式编程)
const buyMilkTea = (type) => new Promise((resolve, reject) => {
  if (type === '芋泥波波') {
    setTimeout(() => resolve('芋泥波波奶茶'), 1000);
  } else {
    reject(new Error('没有这种奶茶'));
  }
});

buyMilkTea('芋泥波波')
  .then(tea => addPearl(tea))
  .then(withPearl => addSugar(withPearl))
  .then(sweetened => console.log('喝到了!', sweetened))
  .catch(error => console.log('翻车了', error));

⏳ async/await:让代码像咖啡师一样「异步摸鱼」

Promise 虽然好用,但链式调用多了还是像排队买奶茶 —— 你得等上一个then完成才能写下一个。直到async/await出现,代码终于学会了「摸鱼」:

// async/await版买奶茶(摸鱼式编程)
async function makePerfectTea() {
  try {
    const tea = await buyMilkTea('芋泥波波');  // 等奶茶时去刷抖音
    const withPearl = await addPearl(tea);      // 等加珍珠时回微信
    const sweetened = await addSugar(withPearl); // 等加糖时上厕所
    return `完美奶茶:${sweetened}`;
  } catch (error) {
    return `翻车现场:${error.message}`;
  }
}

console.log('先干点别的...');
makePerfectTea().then(console.log); // 输出:先干点别的... 然后过1秒输出奶茶结果

这段代码的精髓在于:await让 JS 引擎去忙别的,就像咖啡师在煮咖啡时顺便擦桌子。注意哦,async函数必须用await,不然就像你点了奶茶却站在柜台前发呆。

📦 模块化:把代码变成「乐高积木」

ES6 之前,JS 文件像一锅乱炖:你得用script标签按顺序引入,要是顺序错了,函数没定义就会报错,就像做饭时先炒菜再开火。ES6 的模块化让代码变成了乐高:

// 奶茶店模块:milkTeaShop.js
export function buyMilkTea(type) { /* 实现代码 */ }
export function addPearl(tea) { /* 实现代码 */ }
// 糖罐模块:sugar.js
export function addSugar(tea, level = '半糖') { /* 实现代码 */ }

// 顾客下单模块:customer.js
import { buyMilkTea, addPearl } from './milkTeaShop.js';
import { addSugar } from './sugar.js';

async function orderTea() {
  const tea = await buyMilkTea('芋泥波波');
  const withPearl = addPearl(tea);
  return addSugar(withPearl);
}

模块化三大好处

  • 🧩 避免变量污染:每个模块都是独立空间,不怕同名函数打架
  • 🚚 按需加载:像点外卖只点需要的菜,不用引入整个菜单
  • 🔧 方便维护:哪个模块出问题就像换乐高零件一样替换

🎯 其他「摸鱼神器」特性速览

箭头函数:省略function的「懒癌写法」

// 传统写法:像写作文要写标题
function double(num) { return num * 2; }
// 箭头函数:像发微信只发关键词
const double = num => num * 2;

// 复杂场景:像写情书要换行
const calculate = (a, b) => {
  const sum = a + b;
  return sum * 2;
};

解构赋值:一键拆包裹的「快递神器」

// 传统拆快递:像拆层层胶带
const tea = { type: '芋泥波波', sugar: '半糖', pearl: true };
const type = tea.type;
const sugar = tea.sugar;
// 解构赋值:像用拆快递刀一划到底
const { type, sugar, pearl } = tea;

// 数组解构更神奇:
const [first, second, ...rest] = ['芋圆', '珍珠', '布丁', '仙草'];
// first=芋圆, second=珍珠, rest=[布丁, 仙草]

模板字符串:告别+号拼接的「文案神器」

// 传统拼接:像用胶带粘碎纸
const name = '芋泥波波';
const sugar = '半糖';
const message = '您点的' + name + '奶茶,' + sugar + ',已送达!';
// 模板字符串:像用打印机直接打
const templateMsg = `您点的${name}奶茶,${sugar},已送达!`;

🚀 实战:用 ES6 + 写一个「摸鱼检测」工具

最后来个实战案例:用 Fetch API(结合 async/await)获取「摸鱼指数」,假装在监控同事(实际是演示代码):

// 摸鱼检测工具:fishDetector.js
import { getEmployeeList } from './employee.js'; // 导入员工列表

// 模拟后端API,返回摸鱼概率(0-1)
async function checkFishProbability(empId) {
  try {
    const response = await fetch(`https://api.fish-detector.com/emp/${empId}`);
    const data = await response.json();
    return data.probability;
  } catch (error) {
    console.error('检测失败', error);
    return 0.5; // 默认50%摸鱼概率
  }
}

// 批量检测所有员工
async function monitorAllEmployees() {
  const employees = await getEmployeeList();
  const results = [];
  
  for (const emp of employees) {
    const prob = await checkFishProbability(emp.id);
    results.push({
      name: emp.name,
      fishProbability: prob,
      status: prob > 0.7 ? '重度摸鱼' : prob > 0.3 ? '偶尔摸鱼' : '认真工作'
    });
  }
  
  // 打印摸鱼报告(用模板字符串)
  const report = results.map(emp => 
    `[${emp.status}] ${emp.name}:摸鱼概率 ${(emp.fishProbability * 100).toFixed(1)}%`
  ).join('\n');
  
  console.log('=== 今日摸鱼报告 ===\n' + report);
  return results;
}

// 执行检测(假装是定时任务)
setInterval(monitorAllEmployees, 60000); // 每分钟检测一次

💡 最后:JS 的「摸鱼哲学」

现代 JS 的这些特性,本质上都是让代码学会「偷懒」——Promise 帮你排队时刷手机,async/await 让你等奶茶时上厕所,模块化让你不用重复造轮子。所以记住:写代码的最高境界,是让代码替你摸鱼

现在就打开你的编辑器,用import导入一个LazyMode模块,开始用 ES6 + 优雅地「画饼」吧!🚀

Logo

欢迎加入DeepSeek 技术社区。在这里,你可以找到志同道合的朋友,共同探索AI技术的奥秘。

更多推荐