@@ -227,22 +227,22 @@ getJSON("/post/1.json").then(
227
227
` Promise.prototype.catch ` 方法是` .then(null, rejection) ` 的别名,用于指定发生错误时的回调函数。
228
228
229
229
``` javascript
230
- getJSON (" /posts.json" ).then (function (posts ) {
230
+ getJSON (' /posts.json' ).then (function (posts ) {
231
231
// ...
232
232
}).catch (function (error ) {
233
233
// 处理 getJSON 和 前一个回调函数运行时发生的错误
234
234
console .log (' 发生错误!' , error);
235
235
});
236
236
```
237
237
238
- 上面代码中,` getJSON ` 方法返回一个Promise对象 ,如果该对象状态变为` Resolved ` ,则会调用` then ` 方法指定的回调函数;如果异步操作抛出错误,状态就会变为` Rejected ` ,就会调用` catch ` 方法指定的回调函数,处理这个错误。另外,` then ` 方法指定的回调函数,如果运行中抛出错误,也会被` catch ` 方法捕获。
238
+ 上面代码中,` getJSON ` 方法返回一个 Promise 对象 ,如果该对象状态变为` Resolved ` ,则会调用` then ` 方法指定的回调函数;如果异步操作抛出错误,状态就会变为` Rejected ` ,就会调用` catch ` 方法指定的回调函数,处理这个错误。另外,` then ` 方法指定的回调函数,如果运行中抛出错误,也会被` catch ` 方法捕获。
239
239
240
240
``` javascript
241
- p .then ((val ) => console .log (" fulfilled:" , val))
242
- .catch ((err ) => console .log (" rejected: " , err));
241
+ p .then ((val ) => console .log (' fulfilled:' , val))
242
+ .catch ((err ) => console .log (' rejected' , err));
243
243
244
244
// 等同于
245
- p .then ((val ) => console .log (" fulfilled:" , val))
245
+ p .then ((val ) => console .log (' fulfilled:' , val))
246
246
.then (null , (err ) => console .log (" rejected:" , err));
247
247
```
248
248
@@ -297,12 +297,12 @@ promise
297
297
// ok
298
298
```
299
299
300
- 上面代码中,Promise在 ` resolve ` 语句后面,再抛出错误,不会被捕获,等于没有抛出。
300
+ 上面代码中,Promise 在 ` resolve ` 语句后面,再抛出错误,不会被捕获,等于没有抛出。因为 Promise 的状态一旦改变,就永久保持该状态,不会再变了 。
301
301
302
- Promise对象的错误具有 “冒泡”性质,会一直向后传递,直到被捕获为止。也就是说,错误总是会被下一个` catch ` 语句捕获。
302
+ Promise 对象的错误具有 “冒泡”性质,会一直向后传递,直到被捕获为止。也就是说,错误总是会被下一个` catch ` 语句捕获。
303
303
304
304
``` javascript
305
- getJSON (" /post/1.json" ).then (function (post ) {
305
+ getJSON (' /post/1.json' ).then (function (post ) {
306
306
return getJSON (post .commentURL );
307
307
}).then (function (comments ) {
308
308
// some code
@@ -519,14 +519,14 @@ var p = Promise.race([p1, p2, p3]);
519
519
下面是一个例子,如果指定时间内没有获得结果,就将Promise的状态变为` reject ` ,否则变为` resolve ` 。
520
520
521
521
``` javascript
522
- var p = Promise .race ([
522
+ const p = Promise .race ([
523
523
fetch (' /resource-that-may-take-a-while' ),
524
524
new Promise (function (resolve , reject ) {
525
525
setTimeout (() => reject (new Error (' request timeout' )), 5000 )
526
526
})
527
- ])
528
- p .then (response => console .log (response))
529
- p .catch (error => console .log (error))
527
+ ]);
528
+ p .then (response => console .log (response));
529
+ p .catch (error => console .log (error));
530
530
```
531
531
532
532
上面代码中,如果5秒之内` fetch ` 方法无法返回结果,变量` p ` 的状态就会变为` rejected ` ,从而触发` catch ` 方法指定的回调函数。
0 commit comments