乐闻世界logo
搜索文章和话题

Why does javascript ES6 Promises continue execution after a resolve?

1个答案

1

In JavaScript, ES6 Promises are a mechanism for handling asynchronous operations. When we say a Promise continues executing after resolution, it means that after a Promise is resolved, the chained methods such as then, catch, or finally will still execute.

This design is primarily to enhance code organization and readability, making asynchronous operations easier to manage. Promises allow us to write asynchronous code in a sequential manner, similar to synchronous code, by chaining multiple asynchronous operations using the then method, where each operation can depend on the result of the previous one. When a Promise is resolved, it executes the callback function provided in the then method.

Let's examine a specific example:

javascript
function getUser(userId) { return new Promise((resolve, reject) => { setTimeout(() => { console.log('Retrieving user data'); resolve({ userId: userId, username: "John" }); }, 1000); }); } function getServices(user) { return new Promise((resolve, reject) => { setTimeout(() => { console.log('Retrieving user services'); resolve(['Email', 'VPN', 'CDN']); }, 1000); }); } function getServiceCost(services) { return new Promise((resolve, reject) => { setTimeout(() => { console.log('Calculating service cost'); resolve(services.length * 100); }, 1000); }); } getUser(101) .then(getServices) .then(getServiceCost) .then(console.log);

In this example, the getUser function is first called and returns a Promise. Once resolved (i.e., user data is retrieved), it invokes the getServices function. Similarly, when the getServices function returns a resolved Promise, it calls the getServiceCost function. Finally, the service cost is logged.

The entire process flows seamlessly, even though each operation is asynchronous, because Promise chaining makes them appear to execute sequentially. This is why Promises continue executing after resolution. This pattern is highly beneficial for handling complex asynchronous logic, resulting in clearer and more maintainable code.

2024年7月28日 18:57 回复

你的答案