IT박스

약속에서 if-else를 처리하는 방법은 무엇입니까?

itboxs 2020. 11. 9. 07:56
반응형

약속에서 if-else를 처리하는 방법은 무엇입니까?


어떤 경우에는 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. 새로운 promise를 시작하는 것이 좋은 생각인지 모르겠습니다. Promise에서 프로세스를 시작합니다.

  2. 마지막에 하나의 함수를 호출하기 위해 두 프로세스가 필요하면 어떻게합니까? 동일한 "터미널"이 있음을 의미합니다.

원래 체인을 유지하겠다는 새로운 약속을 다음과 같이 되돌리려 고했습니다.

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

그러나이 경우에는 그것이 참이든 거짓이든 다음 then이 작동합니다.

그래서, 그것을 처리하는 가장 좋은 방법은 무엇입니까?


함수가 promise를 반환하는 한 제안하는 첫 번째 방법을 사용할 수 있습니다.

아래의 바이올린은 첫 번째로 해결 된 값이 무엇인지에 따라 다른 연결 경로를 취하는 방법을 보여줍니다.

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

조건부 약속 사용을위한 간단한 패키지를 작성했습니다.

확인하고 싶다면 :

npm 페이지 : https://www.npmjs.com/package/promise-tree

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

패키지가 문제를 어떻게 해결하는지 묻는 의견에 대한 응답 :

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.

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

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.

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.

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

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.


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

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

});

참고URL : https://stackoverflow.com/questions/33257412/how-to-handle-the-if-else-in-promise-then

반응형