这里来试着创建自己的 Promise
来处理看看非同步 ~
首先用函式建构式创建函式,接着 return
一个 new Promise
,并把 resolve(成功)
reject(失败)
,两个参数传入,对应要执行的程式码,而 num
参数,是要判断的真假值,如果是真值,就调用 resolve
,反之则调用 reject
function promiseFn(num){ return new Promise((resolve, reject) => { setTimeout(() => { if(num){ resolve(`success,${num}`); }else{ reject('fail'); } },10); })}
执行完上面的建立之后,接着就可以来呼叫此函式了
首先先代入 1
这个真值:
promiseFn(1).then((res) => { console.log(res);}).catch((res) => { console.log(res);});// success,1
跑完之后 console
就会出现预期的 success,就是走成功这条路,使用 then()
这个方法并调用 resolve
如果代入 0
这个假值,就会走失败这条路,使用 catch()
方法调用 reject
链接技巧 Promise chain
在执行非同步的时候,有时候会需要依序执行很多程式码,这时候就可以使用到链接技巧也就是 Promise chain
promise
的建构,以最上面的 function
建构式继续当例子,然后传入真假值来决定 resolve
和 reject
全部都是成功(resolve)的情况下链接
promiseFn(1).then((res) => { console.log(res); return promiseFn(2)}).then((res) => { console.log(res);}).catch((res) => { console.log(res);});// success,1// success,2
上述先代入了 1
真值,所以走了 then()
这个方法,当要链接第二个非同步即可以在 then()
下方 return
要执行的非同步 code,这里使用同样的 function
,第二次代入了 2
真值,这时候一样会使用 then()
这个方法,所以在原先的 then()
下方再多了一个 then()
同理,如果都是走成功这条路,只要依序的 return
接着依序的链接 then()
即可。
一开始就是失败(reject)的情况下链接
promiseFn(0).then((res) => { console.log(res);}).catch((res) => { console.log(res); return promiseFn(1)}).then((res) => { console.log(res);})// fail// success,1
这里是一开始就代入了 0
假值,直接走了 catch()
这个方法,然而要链接的时候,一样 return
要执行的 code 且在下方补一个 then()
即可。
如果中途有一个失败(reject)的情况下链接
promiseFn(1).then((res) => { console.log(res); return promiseFn(0)}).then((res) => { console.log(res); return promiseFn(2)}).then((res) => { console.log(res);}).catch((res) => { console.log(res);})// success,1// fail
这里会发现执行顺序有点特别,如果在途中有一个失败调用了 catch()
,就会发现上面链接再多的 then()
都会直接被切断,仅会执行到 catch()
前一笔的 then()
。
颠覆你想像的 then,原来还可以这样用
前面讲到了 promise
只有两条路,要就是成功 resolve
要就是失败 reject
,然后再各别调用 .then()
和 .catch()
但这里要颠覆一下前面讲的 ...
要说说 then
其实还可以这样用,它可以同时塞入两个 callBack function
意即可以接收成功和失败两种结果
所以当不知道非同步会产生哪种结果,而又要使用到链接(promise chain)
的时候就可以这样做了:
promiseFn(0).then((res)=>{ console.log(res)},(res)=>{ console.log(res)})
上述第一个 callBack function
是执行成功的结果,第二个 callBack function
是执行失败的结果,所以当代入 0
这个假值时,就会使用第二个 callBack function
,而此时如果要做链接,在第一个 callBack function
跟第二个 callBack function
都做 return
就可以了,下方一样再补一个 then
即可,如下:
promiseFn(0).then((res)=>{ console.log(res) return promiseFn(2)},(res)=>{ console.log(res) return promiseFn(3)}).then((res)=>{ console.log(res)},(res)=>{ console.log(res)})// fail// success,3
到这里 then
可以说是矛盾阿~~~