2016-10-19 3 views
2

내 머리를 포장하는 데 문제가 주위 비동기/await를 구문비동기/기다리고 있습니다 예상되는 동작

이 코드에 "연결"심지어 콘솔에 기록 얻을 않는 이유를 내가 알아낼 수없는 것은 mysql 연결에 오류가있는 경우.

mongoose.Promise = Promise; 
function connection() { 
    //return a promise to be consumed in an async function 
    return new Promise((resolve, reject) => { 
     mongoose.connect('mongodb://localhost/testdatabase'); 
     let db = mongoose.connection; 
     let sw = mysql.createConnection({ 
      host: 'localhost', 
      user: 'reporting', 
      Promise: Promise, 
      database: 'testdatabase' 
     }); 

     //Only resolve if both database connections are made successfully 
     sw.then(() => { 
      db.on('error', (err) => { 
       reject(err); 
      }); 
      db.once('open',() => { 
       resolve(db); 
      }); 
     }).catch((e) => { 

      reject(e); 
     }) 
    }); 
} 

//Await connection and return true or false for more synchronous code style 
async function connect() { 
    let connected = false; 
    try { 
     //should pause execution until resolved right? 
     await connection(); 
     connected = true; 

    } catch (e) { 
     //Makes it here successfully 
     console.error(e); 
     connected = false 
    } finally { 
     return connected 
    } 
} 

if (connect()) { 
    //This code also gets fired? 
    console.log('connected'); 
} 

답변

3

그들이 반환하기 전에 대기 마술 아무것도 차단하거나하지 않습니다, async function의 여전히 비동기 것을 기억하십시오. connect()을 항상 으로 호출하면이라는 약속이 항상 true이므로 모든 경우에 "연결됨"이 즉시 기록됩니다. 당신이 연결을 위해 대기 할 경우

, 당신은 await에 결과를해야합니다뿐만 아니라 async functionif 문을 포장 :

async function connect() { 
    try { 
     await connection(); 
     return true; 
    } catch (e) { 
     console.error(e); 
     return false 
    } 
} 

(async function() { 
    if (await connect()) { 
//  ^^^^^ 
     console.log('connected'); 
    } 
}()); 
+0

감사합니다. 비동기 함수가 반환한다는 것을 알지 못했습니다. 나는 이것이 Promise보다 훨씬 더 좋은지 잘 모르겠습니다. 그렇다면 패러다임. – richbai90

+0

@ richbai90 그것은'then' 호출을 중첩하지 않고 제어 구조를 사용할 수있게하는 문법적 설탕입니다. 그러나 의미는 동일하게 유지됩니다. 'await'없이 어떻게 보이는지에 대한 아래의 nem035의 대답을보십시오. – Bergi

1

비동기 기능을 약속 때문에이

if (connect()) { // <--- connect() will return a promise 
    // and a promise always evaluates to a truthy value, 
    // that's why this code always runs 
    console.log('connected'); 
} 
에게 반환

수 :

connect().then(isConnected => { 
    if (isConnected) { 
    console.log('connected'); 
    } 
}); 

아니면 Bergi demonstrated in his answer처럼 connect()에서 반환 된 약속을 기다릴 수 있습니다.

관련 문제