下面的小提琴显示了如何根据第一个解析的值采用不同的链接路径。
function myPromiseFunction() { //Change the resolved value to take a different path return Promise.resolve(true);}function conditionalChaining(value) { if (value) { //do something return doSomething().then(doSomethingMore).then(doEvenSomethingMore); } else { //do something else return doSomeOtherThing().then(doSomethingMore).then(doEvenSomethingMore); }}function doSomething() { console.log("Inside doSomething function"); return Promise.resolve("This message comes from doSomeThing function");}function doSomeOtherThing() { console.log("Inside doSomeOtherthing function"); return Promise.resolve("This message comes from doSomeOtherThing function");}function doSomethingMore(message) { console.log(message); return Promise.resolve("Leaving doSomethingMore");}function doEvenSomethingMore(message) { console.log("Inside doEvenSomethingMore function"); return Promise.resolve();}myPromiseFunction().then(conditionalChaining).then(function () { console.log("All done!");}).catch (function (e) {});
您也可以只进行一个条件链接,将返回承诺分配给变量,然后继续执行应以任何一种方式运行的功能。
function conditionalChaining(value){ if (value) { //do something return doSomething(); } else{ //do something else return doSomeOtherThing(); }}var promise = myPromiseFunction().then(conditionalChaining);promise.then(function(value){ //keep executing functions that should be called either way});
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)