IT박스

약속의 가치에 접근하는 방법?

itboxs 2020. 8. 2. 17:52
반응형

약속의 가치에 접근하는 방법?


나는 Angular의 문서 에서이 예제를보고 $q있지만 이것이 일반적으로 약속에 적용될 것이라고 생각합니다. 아래 예제는 주석이 포함 된 문서에서 그대로 복사됩니다.

promiseB = promiseA.then(function(result) {
  return result + 1;
});

// promiseB will be resolved immediately after promiseA is resolved and its value
// will be the result of promiseA incremented by 1

어떻게 작동하는지 잘 모르겠습니다. .then()첫 번째 결과를 호출 하여 .then()연결할 수있는 체인을 연결하면 promiseB유형의 약속 객체입니다 Object. 이 아닙니다 Number. "그 값은 promiseA의 결과가 1 씩 증가합니다"라는 의미는 무엇입니까?

내가 그런 식으로 접근 promiseB.value해야합니까? 성공 콜백은 어떻게 약속을 반환하고 "결과 + 1"을 반환 할 수 있습니까? 뭔가 빠졌습니다.


promiseAthen함수는 promiseB해결 된 후 즉시 해결 되는 새로운 약속 ( )을 반환하며 promiseA, 그 값은에있는 성공 함수에서 반환 된 값입니다 promiseA.

이 경우 promiseA값으로 확인 된 result다음 즉시 promiseB값으로 확인 result + 1됩니다.

에 대한 액세스는 promiseB의 결과에 액세스하는 것과 같은 방식으로 수행됩니다 promiseA.

promiseB.then(function(result) {
    // here you can use the result of promiseB
});

약속이 해결 / 거부되면 성공 / 오류 처리기를 호출합니다.

var promiseB = promiseA.then(function(result) {
   // do something with result
});

then메소드는 promise : promiseB를 리턴하며 promiseA 의 성공 / 오류 핸들러의 리턴 값에 따라 해결 / 거부 됩니다.

promiseA의 성공 / 오류 핸들러가 promiseB의 결과에 영향을 줄 수있는 세 가지 가능한 값이 있습니다.

1. Return nothing --> PromiseB is resolved immediately, 
   and undefined is passed to the success handler of promiseB
2. Return a value --> PromiseB is resolved immediately,
   and the value is passed to the success handler of promiseB
3. Return a promise --> When resolved, promiseB will be resolved. 
   When rejected, promiseB will be rejected. The value passed to
   the promiseB's then handler will be the result of the promise

이러한 이해를 바탕으로 다음을 이해할 수 있습니다.

promiseB = promiseA.then(function(result) {
  return result + 1;
});

then 호출은 promiseB를 즉시 반환합니다. promiseA가 해결되면 결과를 promiseA의 성공 처리기로 전달합니다. 리턴 값은 promiseA의 결과 + 1이므로 성공 핸들러는 값 (위의 옵션 2)을 리턴하므로 promiseB는 즉시 해결되며 promiseB의 성공 핸들러는 promiseA의 결과 + 1을 전달합니다.


.thenpromiseB의 함수는 promiseA의 함수에서 반환 된 내용 .then을받습니다.

여기서 promiseA가 반환하는 숫자 number는 promiseB의 성공 함수에서 매개 변수 로 사용할 수 있습니다 . 그런 다음 1 씩 증가합니다


의견을 현재 이해하는 것과 약간 다르게 해석하면 도움이 될 수 있습니다.

// promiseB will be resolved immediately after promiseA is resolved

이것은 promiseB약속이지만 해결 된 직후에 해결 될 것임을 나타 promiseA냅니다. 이를 보는 또 다른 방법 promiseA.then()은에 지정된 약속을 반환 한다는 의미입니다 promiseB.

// and its value will be the result of promiseA incremented by 1

이는 promiseA해결 된 값이 promiseBsuccessCallback 값으로 수신되는 값임을 의미합니다.

promiseB.then(function (val) {
  // val is now promiseA's result + 1
});

promiseA(pram).then(
     result => { 
     //make sure promiseA function allready success and response
     //do something here
}).catch(err => console.log(err)) => {
     // handle error with try catch
}

자바 스크립트에서 비동기 대기 메소드를 사용하여 쉽게 수행 할 수 있습니다.

아래는 시간 종료를 사용하여 WebRTC 약속 값을 검색하는 예입니다.

function await_getipv4(timeout = 1000) {
    var t1 = new Date();
    while(!window.ipv4) {
        var stop = new Date() - t1 >= timeout;
        if(stop) {
            console.error('timeout exceeded for await_getipv4.');
            return false;
        }
    }
    return window.ipv4;
}

function async_getipv4() {
    var ipv4 = null;
    var findIP = new Promise(r=>{var w=window,a=new (w.RTCPeerConnection||w.mozRTCPeerConnection||w.webkitRTCPeerConnection)({iceServers:[]}),b=()=>{};a.createDataChannel("");a.createOffer(c=>a.setLocalDescription(c,b,b),b);a.onicecandidate=c=>{try{c.candidate.candidate.match(/([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/g).forEach(r)}catch(e){}}})
    findIP.then(ip => window.ipv4 = ip);
    return await_getipv4();
};


pixelbits 응답은 정확하며 항상 .then()프로덕션 코드에서 약속의 가치에 액세스하는 데 사용해야 합니다.

그러나 지원되지 않는 다음 내부 node.js 바인딩을 사용하여 약속 값을 해결 한 후 바로 약속 값에 액세스 할 수 있습니다.

process.binding('util').getPromiseDetails(myPromise)[1]

WARNING: process.binding was never meant to be used outside of nodejs core and the nodejs core team is actively looking to deprecate it

https://github.com/nodejs/node/pull/22004 https://github.com/nodejs/node/issues/22064


This example I find self-explanatory. Notice how await waits for the result and so you miss the Promise being returned.

cryA = crypto.subtle.generateKey({name:'ECDH', namedCurve:'P-384'}, true, ["deriveKey", "deriveBits"])
Promise {<pending>}
cryB = await crypto.subtle.generateKey({name:'ECDH', namedCurve:'P-384'}, true, ["deriveKey", "deriveBits"])
{publicKey: CryptoKey, privateKey: CryptoKey}

In the Node REPL, to get a DB connection that was the value of a promise, I took the following approach:

let connection
try {
  (async () => {
    connection = await returnsAPromiseResolvingToConnection()
  })()
} catch(err) {
  console.log(err)
}

The line with await would normally return a promise. This code can be pasted into the Node REPL or if saved in index.js it can be run in Bash with

node -i -e "$(< index.js)"

which leaves you in the Node REPL after running the script with access to the set variable. To confirm that the asynchronous function has returned, you can log connection for example, and then you're ready to use the variable. One of course wouldn't want to count on the asynchronous function being resolved yet for any code in the script outside the asynchronous function.


Maybe this small Typescript code example will help.

private getAccount(id: Id) : Account {
    let account = Account.empty();
    this.repository.get(id)
        .then(res => account = res)
        .catch(e => Notices.results(e));
    return account;
}

Here the repository.get(id) returns a Promise<Account>. I assign it to the variable account within the then statement.

참고URL : https://stackoverflow.com/questions/29516390/how-to-access-the-value-of-a-promise

반응형