# 需要真正明白的Promise_亿码酷站_编程开发技术教程

【亿码酷站-编程开发教程】收集全网优质教程及源码资源！ Promise 关于 API 这块大家应该都能熟练使用，但是和微任务相关的你可能还存在知识盲区。

## 前置知识

### Promise 哪些 API 涉及了微任务？

Promise 中只有涉及到状态变更后才需要被执行的回调才算是微任务，比如说 `then``catch``finally` ，其他所有的代码执行都是宏任务（同步执行）。

### 这些微任务何时被加入微任务队列？

• 如果此时 Promise 状态为 pending，那么成功或失败的回调会分别被加入至 `[[PromiseFulfillReactions]]``[[PromiseRejectReactions]]` 中。如果你看过手写 Promise 的代码的话，应该能发现有两个数组存储这些回调函数。

• 如果此时 Promise 状态为非 pending 时，回调会成为 Promise Jobs，也就是微任务。

## 初级

```Promise.resolve()
.then(() => {    console.log("then1");    Promise.resolve().then(() => {      console.log("then1-1");
});
})
.then(() => {    console.log("then2");
});复制代码```

## 中级

```let p = Promise.resolve();

p.then(() => {  console.log("then1");  Promise.resolve().then(() => {    console.log("then1-1");
});
}).then(() => {  console.log("then1-2");
});

p.then(() => {  console.log("then2");
});

```let p = Promise.resolve().then(() => {  console.log("then1");  Promise.resolve().then(() => {    console.log("then1-1");
});
}).then(() => {  console.log("then2");
});

p.then(() => {  console.log("then3");
});复制代码```

## 高级

```Promise.resolve()
.then(() => {    console.log("then1");    Promise.resolve()
.then(() => {        console.log("then1-1");        return 1;
})
.then(() => {        console.log("then1-2");
});
})
.then(() => {    console.log("then2");
})
.then(() => {    console.log("then3");
})
.then(() => {    console.log("then4");
});复制代码```

• 第一次 `resolve` 后第一个 `then` 的回调进入微任务队列并执行，打印 `then1`

• 第二次 `resolve` 后内部第一个 `then` 的回调进入微任务队列，此时外部第一个 `then` 的回调全部执行完毕，需要将外部的第二个 `then` 回调也插入微任务队列。

• 执行微任务，打印 `then1-1``then2`，然后分别再将之后 `then` 中的回调插入微任务队列

• 执行微任务，打印 `then1-2``then3` ，之后的内容就不一一说明了

```Promise.resolve()
.then(() => {    console.log("then1");    Promise.resolve()
.then(() => {        console.log("then1-1");        return Promise.resolve();
})
.then(() => {        console.log("then1-2");
});
})
.then(() => {    console.log("then2");
})
.then(() => {    console.log("then3");
})
.then(() => {    console.log("then4");
});复制代码```

PS：`then` 返回一个新的 Promise，并且会用这个 Promise 去 `resolve` 返回值，这个概念需要大家先了解一下。

### 根据 Promise A+ 规范

```if (x instanceof MyPromise) {  if (x.currentState === PENDING) {
} else {
x.then(resolve, reject);
}  return;
}复制代码```

### 根据 ECMA – 262 规范

This Job uses the supplied thenable and its then method to resolve the given promise. This process must take place as a Job to ensure that the evaluation of the then method occurs after evaluation of any surrounding code has completed.
{"ft_lang_label":"__label__zh","ft_lang_prob":0.7531262,"math_prob":0.9100692,"size":3845,"snap":"2022-05-2022-21","text_gpt3_token_len":2150,"char_repetition_ratio":0.27466807,"word_repetition_ratio":0.1853786,"special_character_ratio":0.2803641,"punctuation_ratio":0.19864176,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9575083,"pos_list":[0,1,2,3,4],"im_url_duplicate_count":[null,5,null,5,null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2022-05-27T22:08:27Z\",\"WARC-Record-ID\":\"<urn:uuid:4546f372-3170-449f-ba5a-9878d0ce4916>\",\"Content-Length\":\"74506\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:80f95ce6-7704-4451-a099-4c1883299819>\",\"WARC-Concurrent-To\":\"<urn:uuid:1883b402-6c62-43f0-b3e0-abe3bc50765b>\",\"WARC-IP-Address\":\"156.240.109.236\",\"WARC-Target-URI\":\"https://www.ymkuzhan.com/683.html\",\"WARC-Payload-Digest\":\"sha1:34T3CVA7FOPOJDYRFXXX7C3Q2TGC6FVD\",\"WARC-Block-Digest\":\"sha1:VMZBXDTHWXVNUXFYSOBX34LTALKLHJBQ\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2022/CC-MAIN-2022-21/CC-MAIN-2022-21_segments_1652663006341.98_warc_CC-MAIN-20220527205437-20220527235437-00324.warc.gz\"}"}