2017-11-11 1 views

답변

0

노드가 그것이 동기 코드 인 것처럼 논리적으로 동작 즉, 비동기에 대한 코드의 다음 행으로 계속 진행하기 전에 반환 r.table(... 명령을 기다릴 것을 의미합니다.

RethinkDB가 지정된 키가있는 첫 번째 '사용자'문서를 찾을 때 특정 명령이 반환되어야합니다. 결과를 찾지 못하면 "중지"할 필요가 없습니다. (a) 결과를 찾거나 (b) 전체 테이블을 완료하는 즉시 중지 할 것입니다.

일반적으로 노드/자바 스크립트에서 비동기 코드를 "중지"하는 것은 불가능하지만 비동기 메소드를 기다리는 시간을 제한 할 수 있습니다. 다음은 Promise.race() 함수를 사용하는 예제입니다.

/* 
* toy async function 
* 
* returns a promise that resolves to the specified number `n` 
* after the specified number of seconds `s` (default 2) 
*/ 
const later = (n, s=2) => { 
    return new Promise(resolve => { 
     setTimeout(() => resolve(n), s*1000); 
    }) 
} 

/* 
* returns a promise that rejects with `TIMEOUT_ERROR` after the 
* specified number of seconds `s` 
*/ 
const timeout = (s) => { 
    return new Promise((resolve, reject) => { 
     setTimeout(() => reject("TIMEOUT_ERROR"), s*1000) 
    }) 
} 

/* 
* Example 1: later finished before timeout 
* later resolves after 1 second, timeout function rejects after 3 seconds 
* so we end up in the `.then` block with `val == 42` 
*/ 
Promise.race([later(42, 1), timeout(3)]) 
    .then(val => { 
     // do somethign with val... 
     console.log(val) 
    }).catch(err => { 
     if (err === "TIMEOUT_ERROR") { 
      console.log("we timed out!") 
     } else { 
      consle.log("something failed (but it was not a timeout)") 
     } 
    }); 

/* 
* Example 2 (using async/await syntax): we timeout before later returns. 
* later resolves after 3 seconds, timeout function rejects after 2 seconds 
* so we end up in the `.catch` block with `err == "TIMEOUT_ERROR"` 
*/ 
try { 
    const val = await Promise.race([later(11, 3), timeout(2)]); 
    // do something with val... 
} catch (err) { 
    if (err === "TIMEOUT_ERROR") { 
     console.error("we timed out!") 
    } else { 
     console.error("something failed (but it was not a timeout)") 
    } 
} 
관련 문제