How to access the value of a promise?

后端 未结 12 2275
予麋鹿
予麋鹿 2020-11-22 06:55

I\'m looking at this example from Angular\'s docs for $q but I think this probably applies to promises in general. The example below is copied verbatim from the

相关标签:
12条回答
  • 2020-11-22 07:09

    pixelbits answer is correct and you should always use .then() to access the value of a promise in production code.

    However, there is a way to access the promise's value directly after it has been resolved by using the following unsupported internal node.js binding:

    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

    0 讨论(0)
  • 2020-11-22 07:14

    .then function of promiseB receives what is returned from .then function of promiseA.

    here promiseA is returning is a number, which will be available as number parameter in success function of promiseB. which will then be incremented by 1

    0 讨论(0)
  • 2020-11-22 07:17

    You can easily do that using an async wait method in javascript.

    Below is an example retrieving a WebRTC promise value using a timeout.

    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();
    };

    0 讨论(0)
  • 2020-11-22 07:21

    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.

    0 讨论(0)
  • 2020-11-22 07:21

    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.

    0 讨论(0)
  • 2020-11-22 07:23

    Parsing the comment a little differently than your current understanding might help:

    // promiseB will be resolved immediately after promiseA is resolved
    

    This states that promiseB is a promise but will be resolved immediately after promiseA is resolved. Another way of looking at this means that promiseA.then() returns a promise that is assigned to promiseB.

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

    This means that the value that promiseA resolved to is the value that promiseB will receive as its successCallback value:

    promiseB.then(function (val) {
      // val is now promiseA's result + 1
    });
    
    0 讨论(0)
提交回复
热议问题