Home > Web Front-end > JS Tutorial > How Do I Access the Resolved Value of a Promise Chain in JavaScript?

How Do I Access the Resolved Value of a Promise Chain in JavaScript?

Susan Sarandon
Release: 2025-01-04 13:40:39
Original
1012 people have browsed it

How Do I Access the Resolved Value of a Promise Chain in JavaScript?

Understanding Promise Chaining and Value Access

When working with promises in JavaScript frameworks like Angular, you may come across asynchronous functions that return promises, like the example from Angular's $q documentation:

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

While the documentation states that "promiseB will be resolved immediately after promiseA is resolved... with the result of promiseA incremented by 1," it may not be clear how this works.

The key to understanding this is to recognize that the then function in promiseA returns a new promise, promiseB. This new promise is resolved immediately after promiseA resolves, and its value is determined by the return value of the success function within promiseA.

In this case, the success function returns "result 1," so promiseB will resolve with the value of result incremented by 1. Therefore, to access this value, you can do the following:

promiseB.then(function(result) {
    // Here you can use the result of promiseB
});
Copy after login

In modern JavaScript versions (ES7 and above), you can use the async/await syntax to achieve the same functionality:

async function doSomething() {
    let result = await functionThatReturnsPromiseA();
    return result + 1;
}
Copy after login

In this case, await unwraps the result from promiseA and assigns it directly to the result variable, allowing you to work with the value without accessing the promise object.

Note that async/await can only be used within async functions, which always return promises. Therefore, if you want to access the return value of an async function, you must use await within another async context.

The above is the detailed content of How Do I Access the Resolved Value of a Promise Chain in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template