2016-06-03 5 views
-3

node.js에서 promise를 사용하는 방법에 대한 예제가 필요합니다. 함수 호출을 마친 후에 닫아야하는 변수 연결이 있습니다. 여기 내 프로그램이node.js에서 Promise를 사용하는 예제가 필요합니다.

var connection = { 
    /*create connection */ 
} 

/* call to a function */ 

/* close connection after function finish */ 
connection.close(); 
+0

이 약속에 대한이 기사를 읽기 : https://strongloop.com/strongblog/promises-in -node-js-with-q-an-alternative-callbacks/ – kaxi1993

+0

'callToAFunction(). callToAFunction'이 약속을 반환한다고 가정하면 (() => connection.close())'입니다. –

+0

나는'function (data) {console.log ('done'); }''안에''하지만''새로운 promise (function (resolve, reject) {})를 반환했습니다. '라는 함수에서도 작동하지 않았습니다. –

답변

0

이것은 블루 버드를 사용하는 예입니다 실행 방법 흐름이 (http://bluebirdjs.com/docs/getting-started.html)

let con = undefined 

Promise.try(() => createConnection()) // create connection 
    .then(_con => { 
    con = _con // assign connection 

    // TO DO STUFF 
    }) 
    .then(() => { 
    con.close() // close connection 
    }) 
    .catch(e => { 
    // handle exception here 
    }) 
관련 문제