promise、setTimeout混搭的 JavaScript 运行机制
笔试题总考,一次又一次再见面的兄弟 promise 和 setTimeout真让人欲罢不能(雾)。真的受不了每次浑水摸鱼猜(真实),这次看了各有趣的总结,在此做个总结!!
参考: https://juejin.im/post/59e85eebf265da430d571f89#heading-3
首先先要知道 promise 是个啥玩意(喂,难道没有弄清楚就冲了吗?)
Promise 对象是一个构造函数。
- resolve 和 reject 是两个函数,JavaScript 引擎提供,不需要自己部署。
- 在 promise 函数内,这两个函数是用来改变 promise 的状态。状态只要改变就不受外界影响再改变。(超级奈斯有没有 QvQ )
- 比如:在异步调用成功之后,需要将 promise 状态改为 fulfilled,就要用 resolve(), 如果是异步调用失败之后嫩,就需要将 promise 状态改为 rejected,就需要调用 reject()
const isCheck = true;
const pro1 = function(tem) {
const message = "hey gay!" + tem.height + " " + tem.color;
return Promise.resolve(message);
};
const pro2 = new Promise((resolve,reject) => {
if (isCheck) {
const tem = {
height: '111',
color: 'red'
};
console.log("pro2.resolve");
return resolve