blob: e48243fcc9819bb17778b4cd1b2a7243cd69b3f4 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
|
---
title: Promise() 构造器
slug: Web/JavaScript/Reference/Global_Objects/Promise/Promise
translation_of: Web/JavaScript/Reference/Global_Objects/Promise/Promise
---
<div>{{JSRef}}</div>
<p><strong><code>Promise</code></strong> 构造器主要用于包装不支持promise(返回值不是<code>Promise</code>)的函数。</p>
<div>{{EmbedInteractiveExample("pages/js/promise-constructor.html")}}</div>
<p class="hidden">交互式的demo的源码在GitHub仓库,如果你乐于为交互式的demo做贡献,请克隆<a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a>并提交pull request .</p>
<h2 id="语法">语法</h2>
<pre class="syntaxbox">new Promise(<var>executor</var>)</pre>
<h3 id="参数">参数</h3>
<dl>
<dt><code>executor</code></dt>
<dd>这是一个双参函数,参数为<code>resolve<font face="Arial, x-locale-body, sans-serif"><span style="background-color: #ffffff;">和</span></font>reject</code>。<code>Promise</code>的实现会立即执行<code>executor</code>,并传入<code>resolve<font face="Arial, x-locale-body, sans-serif"><span style="background-color: #ffffff;">和</span></font>reject</code>函数(<code>Promise</code>构造器将会在返回新对象之前<code>executor</code>)。当<code>resolve</code>和<code>reject</code>函数被调用时,它们分别对promise执行<code>resolve</code>和<code>reject</code>。<code>executor</code>通常会触发一些异步运算,一旦运算成功完成,则<code>resolve</code>掉这个promise,如果出错则<code>reject</code>掉。如果<code>executor</code>函数执行时抛出异常,promise状态会变为<code>rejected</code>。<code>executor</code>的返回值也会被忽略。</dd>
</dl>
<h2 id="例子">例子</h2>
<p>我们通过<code>new</code>关键字和<code>Promise</code>构造器创建它的对象。这个构造器接受一个名为"executor function"的函数。这个函数应当接受两个函数参数。当异步任务成功时,第一个函数(<code>resolve</code>)将被调用,并返回一个值代表成功。当其失败时,第二个函数(<code>reject</code>)将被调用,并返回失败原因(失败原因通常是一个error对象)。</p>
<pre class="brush: js;">const myFirstPromise = new Promise((resolve, reject) => {
// do something asynchronous which eventually calls either:
//
// resolve(someValue) // fulfilled
// or
// reject("failure reason") // rejected
});
</pre>
<p>为了提供一个拥有promise功能的函数,简单的返回一个promise即可:</p>
<pre class="brush: js;">function myAsyncFunction(url) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest()
xhr.open("GET", url)
xhr.onload = () => resolve(xhr.responseText)
xhr.onerror = () => reject(xhr.statusText)
xhr.send()
});
}</pre>
<h2 id="说明">说明</h2>
<table class="standard-table">
<tbody>
<tr>
<th scope="col">Specification</th>
</tr>
<tr>
<td>{{SpecName('ESDraft', '#sec-promise-constructor', 'Promise constructor')}}</td>
</tr>
</tbody>
</table>
<h2 id="浏览器兼容性">浏览器兼容性</h2>
<p>{{Compat("javascript.builtins.Promise.Promise")}}</p>
<h2 id="See_also">See also</h2>
<ul>
<li><a href="/en-US/docs/Web/JavaScript/Guide/Using_promises">Using Promises</a></li>
</ul>
|