From cf6b7c2e6744f2332a2da8beecb5f7f122f8e049 Mon Sep 17 00:00:00 2001 From: Leon Xu <6479451-leonxu260@users.noreply.gitlab.com> Date: Sun, 17 Oct 2021 17:29:44 -0700 Subject: [PATCH] doc: create then and catch return Promise section --- source/_posts/异步JavaScript.md | 56 ++++++++++++++++++++++++++++++++- 1 file changed, 55 insertions(+), 1 deletion(-) 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