2016-08-11 4 views
0

약속을 반환하는 함수가 두 개 있으며 catch 문을 사용하여 오류를 잡아서 더 명확하게 만들고 싶습니다.약속을 반환하는 함수에 대한 호출 만들기

코드가 올바른 순서로 비동기 적으로 함수를 호출한다고해도 올바른 방법이라고 생각합니다.

이들은

내 호출은 다음과 같습니다

// The text is hopefully the email address and the pin number 
fb.verifyEmailPin(text).then(function(reply){ 

    // Set the new state to 'get_city' 
    fb.setState(FB_ID).then(function(result){ 


    }).catch(function(v) { 
     // Rejection 
     // If there was an error then prompt the user to enter again 
    }); // setState 

}).catch(function(err){ 

});// verifyEmailPin 

그리고이 실제 기능 - setState를, 나는 아직 verifyEmailPin 기능에 대한 코드를 작성하지 않은하지만 측면에서 설정 상태와 동일한 구조를 다음과 해결하거나 거절 함.

/* 
* Function : setState 
* Purpose : Set the state to what every is send in on the parameter 
*/ 
exports.setState = function(fbid,newstate){ 

    var success = 'Y'; 
    return new Promise((resolve, reject) => { 

    client.hmset(fbid, { 'state': newstate }); 

    // Check that we have set it ok 
    client.hmget(fbid,'state',function(err,reply){ 

     if (err || reply != newstate) { 
      return reject(err); 
     } 

     return resolve(success); 

    }); 


    }).catch(function(v) { 

    }); 

} 
+0

* "코드가 비동기 적으로 올바른 순서로 함수를 호출 않습니다."* -.?. 그래서 문제가 무엇인지 당신은 질문을 한 것으로 보이지 않는다 – nnnnnn

답변

2

끝에 .catch 하나만 사용할 수 있습니다. 그리고 들여 쓰기가 적어지면 .then을 연결할 수 있습니다. 내부에서 비동기식 작업을 수행하는 경우 다음에 -functions가 약속을 반환해야합니다. 그렇지 않으면 다음을 수행하면 완료 될 때까지 기다리지 않습니다. 동기 작업에 (예를 somePromise.then(JSON.parse).then(...)) 어떤 약속이 필요하지 않습니다 여기에

짧은 예제 :.

function promiseTest(x) { 
    Promise.resolve(x).then(function(a) { // instead of Promise.resolve do something asynchronous, e.g. an ajax call that returns a promise 
     if (typeof x != "number") throw "NaN"; 
     return a*2; 
    }).then(function(a) { 
     console.log(a); 
    }).catch(function(err) { 
     console.error("error in promise:", err); 
    }) 
} 
promiseTest(1); //logs 2 to the console 
promiseTest("a"); // shows error message in the console 

병렬로 여러 비동기 작업을 실행하고 의해 Promise.all을 사용할 수 있습니다 완료 그들 모두를 기다려야합니다 약속의 배열을 공급

Promise.all([doSomethingAsyncAndReturnPromise(), somethingElseAsync()]).then(function results) { 
    // results[0] contains the result from doSomethingAsyncAndReturnPromise 
    // results[1] contains the result from somethingElseAsync 
}); 
+0

체인 t처럼 그의 약속은 정말로 당신이 약속을 지울 때받는 가장 큰 이익입니다. 콜백은 단일의 동기식 제어 흐름으로 통합되므로 원하는 경우 한 곳에서 모든 오류 처리를 수행 할 수 있습니다. – Squirrel

+0

이런 식으로 평행하게 실행하지 말고'promiseTest (1)'과'promiseTest ("a")를 연결하면 더 좋을 것이라고 생각합니다. – jib

+0

@jib 그것은'promiseTest'가 약속을 반환하지 않기 때문에 작동하지 않을 것입니다. 또한, 여러 약속을 평행하게하는 것 ('Promise.all'은 정말 깔끔합니다.)이 전혀 다르지 않고 다른 약속에서 계속 진행되는 일들을 방해하지 않는다면 잘못된 것이 없습니다. 그리고 이것은 실제로 콘솔과 테스트 유형의 오픈 브라우져 일 뿐이므로이 함수를 수동으로 호출하여 여러 번 실험 해 볼 수 있습니다. – hsan

관련 문제