# Promise 那些事儿

TIP

TODO 未完待续

# Promise 的历史由来

# JavaScript 中的 Promise

const promise = new Promise((hello, world) => {
  console.log("init");
  setTimeout(() => {
    console.log("------------->pending");
    hello(); // 状态改变,仅此一次
    console.log("fulfilled");
    world();
    return;
    console.log("after return 不会执行");
  }, 0);
  console.log("pending------------->");
});
console.log("同步");
promise
  .then(() => {
    console.log("then");
  })
  .catch(() => {
    console.log("catch");
  });
// init
// 同步
// fulfilled
// then

# Promise 的 A+规范

# Promise 的应用

# Promise 串行执行

function go(num) {
  return function task() {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        console.log(num);
        resolve(num);
      }, 1000);
    });
  };
}

let list = [0, 1, 2, 3, 4, 5];
let tasks = [];

list.forEach((item) => {
  tasks.push(go(item));
});

const serialExecute = async (tasks = []) => {
  const resultList = [];
  for (task of tasks) {
    try {
      resultList.push(await task());
    } catch (e) {
      resultList.push(e);
    }
  }
  return resultList;
};

serialExecute(tasks).then((res) => console.log(res));

# Promise 并发执行

# 学习资料

# 文字

Promise 的前世今生 (opens new window)

Futures_and_promises - Wikipedia (opens new window)

Future 与 promise - 维基百科 (opens new window)

JavaScript 中的异步冒险:Promises (opens new window)

# 视频

尚硅谷 Web 前端 Promise 教程从入门到精通 (opens new window)