Accessing the Value of Promises
Promises are commonly used for asynchronous operations in JavaScript. One of the key methods for interacting with promises is the .then() method. This method allows us to chain multiple promises and access the value of the previous promise in the subsequent promises.
Consider the following Angular example:
promiseB = promiseA.then(function(result) { return result + 1; });
This example defines promiseB as a new promise that is resolved immediately after promiseA is resolved. According to the Angular documentation, "its value will be the result of promiseA incremented by 1."
The question arises: how can a promise object, which is of type Object, hold a primitive value like a number?
The answer lies in the semantics of the .then() method. The success callback function provided to .then() returns a new value which becomes the value of the new promise. In this case, the success callback function returns result 1, which increments the value of result and returns it as the value of promiseB.
To access the value of promiseB, we can chain another .then() method and provide a success callback function:
promiseB.then(function(result) { // Use the result of promiseB here });
In this callback, we will have access to the value of result, which is the incremented value from the previous promise.
ES7 (2016) introduced the async/await syntax, offering an alternative way to handle promises. Using await, we can unwrap the value of the promise directly, eliminating the need for chaining multiple .then() methods. For example:
async function doSomething() { let result = await functionThatReturnsPromiseA(); return result + 1; }
In this example, the await keyword is used in an async function. The await keyword pauses the execution of the function until functionThatReturnsPromiseA() resolves. Once the promise is resolved, the value of the promise is assigned to the result variable and the function continues execution.
The above is the detailed content of How Do Promises, Objects in JavaScript, Hold Primitive Values?. For more information, please follow other related articles on the PHP Chinese website!