那么如何处理if-else呢?

在某些情况下,当我从一个promise对象中得到一个返回值时,我需要根据这个值的条件来启动两个不同的then() ,如:

 promise().then(function(value){ if(//true) { // do something } else { // do something } }) 

我想也许我可以这样写:

 promise().then(function(value){ if(//true) { // call a new function which will return a new promise object ifTruePromise().then(); } else { ifFalsePromise().then(); } }) 

但是有了这个,我有两个问题:

  1. 我不确定是否有一个好的主意来开始一个新的承诺 – 然后是一个承诺的过程;

  2. 如果我需要这两个过程在最后调用一个函数呢? 这意味着他们有相同的“terminal”

我试图返回新的承诺,以保持原来的链像:

 promise().then(function(value){ if(//true) { // call a new function which will return a new promise object // and return it return ifTruePromise(); } else { // do something, no new promise // hope to stop the then chain } }).then(// I can handle the result of ifTruePromise here now); 

但在这种情况下,无论是对还是错,下一步都会起作用。

那么,最好的做法是什么呢?

只要你的函数返回一个承诺,你可以使用你build议的第一个方法。

下面的提琴显示了如何根据第一个parsing的值将采取不同的链接path。

 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) { }); 

我已经写了一个简单的包有条件诺言用法。

如果你想看看:

npm页面: https ://www.npmjs.com/package/promise-tree

和github: https : //github.com/shizongli94/promise-tree

作为回应,询问如何解决这个问题:

1,它有两个对象。

2,这个包中的分支对象是你想在then()或catch()中使用的onFulfilled和onRejected等函数的临时存储位置。 它具有诸如then()和catch()这样的方法,它们与Promise中的对应方具有相同的参数。 当您在Branch.then()或Branch.catch()中传递callback时,使用与Promise.then()和Promise.catch()相同的语法。 然后,不要做任何事情,只能将callback存储在数组中。

3,Condition是一个JSON对象,用于存储检查和分支的条件和其他信息。

4,您可以在promisecallback中使用条件对象指定条件(布尔expression式)。 条件然后存储你传递的信息。在用户提供了所有必要的信息之后,条件对象使用一种方法来构造全新的Promise对象,该对象承载先前存储在Branch对象中的promise链和callback信息。 这里有一个棘手的部分是你(作为实现者,而不是用户)必须解决/拒绝你先链接存储的callback之前首先手动构build的Promise。 这是因为否则,新的承诺链将无法启动。

5,感谢事件循环,Branch对象可以在你有一个Promise对象之前或之后实例化,它们不会相互干扰。 我在这里使用术语“分支”和“干”,因为结构类似于树。

示例代码可以在npm和github页面上find。

顺便说一句,这个实现也使你有一个分支内的分支机构。 而且分支机构不一定要在你检查条件的地方。