How to access the value of a promise?

后端 未结 12 2297
予麋鹿
予麋鹿 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:26

    When a promise is resolved/rejected, it will call its success/error handler:

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

    The then method also returns a promise: promiseB, which will be resolved/rejected depending on the return value from the success/error handler from promiseA.

    There are three possible values that promiseA's success/error handlers can return that will affect promiseB's outcome:

    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
    

    Armed with this understanding, you can make sense of the following:

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

    The then call returns promiseB immediately. When promiseA is resolved, it will pass the result to promiseA's success handler. Since the return value is promiseA's result + 1, the success handler is returning a value (option 2 above), so promiseB will resolve immediately, and promiseB's success handler will be passed promiseA's result + 1.

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

    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}
    
    0 讨论(0)
  • 2020-11-22 07:28

    promiseA's then function returns a new promise (promiseB) that is immediately resolved after promiseA is resolved, its value is the value of the what is returned from the success function within promiseA.

    In this case promiseA is resolved with a value - result and then immediately resolves promiseB with the value of result + 1.

    Accessing the value of promiseB is done in the same way we accessed the result of promiseA.

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

    Edit December 2019: async/await is now standard in JS, which allows an alternative syntax to the approach described above. You can now write:

    let result = await functionThatReturnsPromiseA();
    result = result + 1;
    

    Now there is no promiseB, because we've unwrapped the result from promiseA using await, and you can work with it directly.

    However, await can only be used inside an async function. So to zoom out slightly, the above would have to be contained like so:

    async function doSomething() {
        let result = await functionThatReturnsPromiseA();
        return result + 1;
    }
    
    0 讨论(0)
  • 2020-11-22 07:28

    I am a slow learner of javascript promises, by default all async functions return a promise, you can wrap your result as:

    (async () => {
    //Optional "await"
      await yourAsyncFunctionOrPromise()
        .then(function (result) {
          return result +1;
        })
        .catch(function (error) {
          return error;
        })()
    })
    

    "The await expression causes async function execution to pause until a Promise is settled (that is, fulfilled or rejected), and to resume execution of the async function after fulfillment. When resumed, the value of the await expression is that of the fulfilled Promise. If the Promise is rejected, the await expression throws the rejected value."

    Read more about await and promises at MDN Web Docs

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

    There are some good answer above and here is the ES6 Arrow function version

    var something = async() => {
       let result = await functionThatReturnsPromiseA();
       return result + 1;
    }
    
    0 讨论(0)
  • 2020-11-22 07:30
    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
    }
    
    0 讨论(0)
提交回复
热议问题