doc: create then and catch return Promise section
This commit is contained in:
1 parent
abc0c7c756
commit
cf6b7c2e67
1 file changed
+55
-1
@@ -256,4 +256,58 @@ orderPizza
|
|||||||
- 响应时间过长或服务器宕机
|
- 响应时间过长或服务器宕机
|
||||||
- 糟糕的网络链接
|
- 糟糕的网络链接
|
||||||
|
|
||||||
无论这些请求是成功还是失败,我们任然希望做出一些反应
|
无论这些请求是成功还是失败,我们任然希望做出一些反应
|
||||||
|
|
||||||
|
# then和catch返回Promise
|
||||||
|
```javascript
|
||||||
|
function executor(resolve) {
|
||||||
|
resolve('Woohoo!');
|
||||||
|
}
|
||||||
|
|
||||||
|
let myPromise = new Promise(executor);
|
||||||
|
let thenPromise = myPromise.then(console.log);
|
||||||
|
let catchPromise = myPromise.catch(console.error);
|
||||||
|
|
||||||
|
console.log(thenPromise instanceof Promise); //true
|
||||||
|
console.log(catchPromise instanceof Promise); //true
|
||||||
|
|
||||||
|
console.log(myPromise === thenPromise); //false
|
||||||
|
console.log(myPromise === catchPromise); //false
|
||||||
|
|
||||||
|
console.log(thenPromise === catchPromise); //false
|
||||||
|
```
|
||||||
|
then和catch返回Promise
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
function executor(resolve) {
|
||||||
|
resolve('Woohoo!');
|
||||||
|
}
|
||||||
|
|
||||||
|
function processStr(val) {
|
||||||
|
return val.toLowerCase().replace('!', '');
|
||||||
|
}
|
||||||
|
|
||||||
|
let myPromise = new Promise(executor);
|
||||||
|
let thenPromise = myPromise.then(processStr);
|
||||||
|
console.log(thenPromise);
|
||||||
|
```
|
||||||
|
processStr返回一个支付穿,然后将其转换为一个Promise,该Promise会立即使用值"woohoo"进行解析。
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
function executor(resolve) {
|
||||||
|
resolve('Woohoo!');
|
||||||
|
}
|
||||||
|
|
||||||
|
function processStr(val) {
|
||||||
|
return new Promise(function (resolve)) {
|
||||||
|
setTimeout(function () {
|
||||||
|
resolve(val.toLowerCase().replace('!', ''));
|
||||||
|
}, 5000);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
let myPromise = new Promise(executor);
|
||||||
|
let thenPromise = myPromise.then(processStr);
|
||||||
|
console.log(thenPromise);
|
||||||
|
```
|
||||||
|
现在,Promise是属于“等待”(PENDING),在processStr返回的promise被解析前不会被解析。
|
||||||
Reference in new issue
Block a user