diff --git a/source/_posts/异步JavaScript.md b/source/_posts/异步JavaScript.md index c5e02a9..0282290 100644 --- a/source/_posts/异步JavaScript.md +++ b/source/_posts/异步JavaScript.md @@ -256,4 +256,58 @@ orderPizza - 响应时间过长或服务器宕机 - 糟糕的网络链接 -无论这些请求是成功还是失败,我们任然希望做出一些反应 \ No newline at end of file +无论这些请求是成功还是失败,我们任然希望做出一些反应 + +# 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被解析前不会被解析。 \ No newline at end of file