node.js 那么如何处理promise中的if-else呢?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33257412/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 19:24:18  来源:igfitidea点击:

How to handle the if-else in promise then?

node.jsasynchronouspromise

提问by Brick Yang

In some case, when I get a return value from a promise object, I need to start two different then()precesses depend on the value's condition, like:

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

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

I'm thinking maybe I can write it like:

我想也许我可以这样写:

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

but with this, I have two questions:

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

  1. I'm not sure if it's a good idea to start a new promise-then process in a promise;

  2. what if I need the two process to call one function in the last? It means they have the same "terminal"

  1. 我不确定在承诺中开始一个新的承诺然后流程是否是一个好主意;

  2. 如果我需要两个进程在最后调用一个函数怎么办?这意味着他们有相同的“终端”

I tried to return the new promise to keep the original chain like:

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

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

but in this case, whether it's true or false, the next thenwill work.

但在这种情况下,无论是真还是假,下一个then都会起作用。

SO, what's the best practice to handle it?

那么,处理它的最佳做法是什么?

采纳答案by Daniel B

As long as your functions return a promise, you can use the first method that you suggest.

只要您的函数返回一个承诺,您就可以使用您建议的第一种方法。

The fiddle below shows how you can take different chaining paths depending on what the first resolved value will be.

下面的小提琴显示了如何根据第一个解析值采用不同的链接路径。

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

});

You can also just make one conditional chaining, assign the return promise to a variable and then keep executing the functions that should be run either way.

您也可以只进行一个条件链接,将返回承诺分配给一个变量,然后继续执行应该以任何一种方式运行的函数。

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

回答by szl1919

I have written a simple package for conditional promise usage.

我已经为条件承诺的使用编写了一个简单的包。

If you want to check it out:

如果你想检查一下:

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

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

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

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

In response of comments asking for how the package solves the problem:

针对询问包如何解决问题的评论:

1, It has two objects.

1、它有两个对象。

2, Branch object in this package is a temporary storage place for the functions such as onFulfilled and onRejected that you want to use in then() or catch(). It has methods such as then() and catch() which take the same arguments as the counterparts in Promise. When you pass in a callback in Branch.then() or Branch.catch(), use the same syntax as Promise.then() and Promise.catch(). Then do nothing but storing the callbacks in an array.

2、这个包中的Branch对象是你要在then()或catch()中使用的onFulfilled和onRejected等函数的临时存放处。它具有 then() 和 catch() 等方法,它们采用与 Promise 中的对应方法相同的参数。在 Branch.then() 或 Branch.catch() 中传入回调时,请使用与 Promise.then() 和 Promise.catch() 相同的语法。然后什么都不做,只是将回调存储在数组中。

3, Condition is a JSON object that stores the conditions and other information for checking and branching.

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

4, You specify conditions (boolean expression) using condition object in promise callbacks. Condition then stores the information you pass in. After all necessary information is provided by user, condition object uses a method to construct completely new Promise object that takes promise chain and callback information previously stored in Branch object. A little tricky part here is that you (as the implementer, not user) have to resolve/reject the Promise you first constructed manually before chaining the stored callbacks. This is because otherwise, the new promise chain won't start.

4、您在promise回调中使用条件对象指定条件(布尔表达式)。然后Condition存储你传入的信息。当用户提供了所有必要的信息后,condition对象使用一个方法构造一个全新的Promise对象,该对象接受之前存储在Branch对象中的promise链和回调信息。这里有点棘手的部分是您(作为实现者,而不是用户)必须在链接存储的回调之前解析/拒绝您首先手动构建的 Promise。这是因为否则,新的承诺链将不会启动。

5, Thanks to event loop, Branch objects can be instantiated either before or after you have a stem Promise object and they won't interfere with each other. I use the terms "branch" and "stem" here because the structure resembles a tree.

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

Example code can be found on both npm and github pages.

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

By the way, this implementation also enables you have branches within a branch. And branches do not have to be at the same place you check conditions.

顺便说一句,此实现还使您可以在分支中拥有分支。并且分支不必与您检查条件的位置相同。

回答by Servus

This is how I did it in my fetch() I am not sure if this is the right way, but it works

这就是我在我的 fetch() 中所做的我不确定这是否是正确的方法,但它有效

 fetch().then(res => res.ok ? res : false).then(res => {
    if (res) {
        //res ok
    } else {
       //res not ok
    }

});