mirror of
https://gitee.com/coder-xiaomo/leetcode-problemset
synced 2025-01-11 02:58:13 +08:00
63 lines
2.3 KiB
HTML
63 lines
2.3 KiB
HTML
|
<p>给定一个异步函数数组 <code>functions</code>,返回一个新的 promise 对象 <code>promise</code>。数组中的每个函数都不接受参数并返回一个 promise。</p>
|
|||
|
|
|||
|
<p><code>promise</code> resolve 条件:</p>
|
|||
|
|
|||
|
<ul>
|
|||
|
<li>当所有从 <code>functions</code> 返回的 promise 都成功解析时。<code>promise</code> 的解析值应该是一个按照它们在 <code>functions</code> 中的顺序排列的 promise 的解析值数组。</li>
|
|||
|
</ul>
|
|||
|
|
|||
|
<p><code>promise</code> reject 条件:</p>
|
|||
|
|
|||
|
<ul>
|
|||
|
<li>当任何从 <code>functions</code> 返回的 promise 被拒绝时。<code>promise</code> 也会被拒绝,并返回第一个拒绝的原因。</li>
|
|||
|
</ul>
|
|||
|
|
|||
|
<p>请在不使用内置的 <code>Promise.all</code> 函数的情况下解决。</p>
|
|||
|
|
|||
|
<p> </p>
|
|||
|
|
|||
|
<p><strong class="example">示例 1:</strong></p>
|
|||
|
|
|||
|
<pre>
|
|||
|
<b>输入:</b>functions = [
|
|||
|
() => new Promise(resolve => setTimeout(() => resolve(5), 200))
|
|||
|
]
|
|||
|
<b>输出:</b>{"t": 200, "resolved": [5]}
|
|||
|
<b>解释:</b>
|
|||
|
promiseAll(functions).then(console.log); // [5]
|
|||
|
|
|||
|
单个函数在 200 毫秒后以值 5 成功解析。
|
|||
|
</pre>
|
|||
|
|
|||
|
<p><strong class="example">示例 2:</strong></p>
|
|||
|
|
|||
|
<pre>
|
|||
|
<b>输入:</b>functions = [
|
|||
|
() => new Promise(resolve => setTimeout(() => resolve(1), 200)),
|
|||
|
() => new Promise((resolve, reject) => setTimeout(() => reject("Error"), 100))
|
|||
|
]
|
|||
|
<b>输出:</b>{"t": 100, "rejected": "Error"}
|
|||
|
<b>解释:</b>由于其中一个 promise 被拒绝,返回的 promise 也在同一时间被拒绝并返回相同的错误。
|
|||
|
</pre>
|
|||
|
|
|||
|
<p><strong class="example">示例 3:</strong></p>
|
|||
|
|
|||
|
<pre>
|
|||
|
<b>输入:</b>functions = [
|
|||
|
() => new Promise(resolve => setTimeout(() => resolve(4), 50)),
|
|||
|
() => new Promise(resolve => setTimeout(() => resolve(10), 150)),
|
|||
|
() => new Promise(resolve => setTimeout(() => resolve(16), 100))
|
|||
|
]
|
|||
|
<b>输出:</b>{"t": 150, "resolved": [4, 10, 16]}
|
|||
|
<b>解释:</b>所有的 promise 都成功执行。当最后一个 promise 被解析时,返回的 promise 也被解析了。
|
|||
|
</pre>
|
|||
|
|
|||
|
<p> </p>
|
|||
|
|
|||
|
<p><strong>提示:</strong></p>
|
|||
|
|
|||
|
<ul>
|
|||
|
<li><code>functions is an array of functions that returns promises</code></li>
|
|||
|
<li><code>1 <= functions.length <= 10</code></li>
|
|||
|
</ul>
|