定义方法 testPromise() { return new Promise((resolve, reject) => { setTimeout(() => { resolve("1"); }, 10000); }); }, testPromie2() { return new Promise((resolve, reject) => { setTimeout(() => { resolve("2"); }, 3000); }); }, 执行 const get1 = this.testPromise(); const get2 = this.testPromie2(); Promise.all([get1]).then((res) => { console.log(res); }); Promise.all([get2]).then((res) => { console.log(res); }); 执行顺序是什么,为什么会这么执行
时间: 2024-04-02 16:05:51 浏览: 24
执行顺序如下:
1. 首先,`testPromise()` 方法会创建一个 Promise 对象,其中包含一个定时器,在 10 秒后将 Promise 解析为值 "1"。
2. 然后,`testPromie2()` 方法会创建另一个 Promise 对象,其中包含一个定时器,在 3 秒后将 Promise 解析为值 "2"。
3. 接下来,`const get1 = this.testPromise()` 会调用 `testPromise()` 方法并将返回的 Promise 对象赋给 `get1`。
4. 同样地,`const get2 = this.testPromie2()` 会调用 `testPromie2()` 方法并将返回的 Promise 对象赋给 `get2`。
5. 然后,`Promise.all([get1])` 会创建一个新的 Promise 对象,并等待 `get1` 的解析结果。
6. 同样地,`Promise.all([get2])` 会创建另一个新的 Promise 对象,并等待 `get2` 的解析结果。
7. 前面的定时器中,`testPromie2()` 的定时器在 3 秒后解析为值 "2",因此会先执行 `console.log(res)`,输出数组 `["2"]`。
8. 然后,`testPromise()` 的定时器在 10 秒后解析为值 "1",继续执行 `console.log(res)`,输出数组 `["1"]`。
总结起来,`testPromise()` 方法的定时器时间较长,所以它的解析结果会在 `testPromie2()` 的解析结果之后输出。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)