


JavaScript Asynchronous Calling Framework (Part 4 - Chained Calling)_javascript skills
In real development, it is very common to perform a series of synchronous and asynchronous operations in sequence. Still using the example in Baidu Hi web version, we first need to asynchronously obtain the contact list, and then asynchronously obtain the specific information of each contact, and the latter is obtained in pages. Each request sends the names of 10 contacts and then Retrieve the corresponding specific information. This is multiple asynchronous requests that need to be executed sequentially.
To this end, we need to design a new operation method to optimize code readability, so that the sequential asynchronous operation code looks as elegant as the traditional sequential synchronous operation code.
Traditional approach
Most programmers can well understand sequential execution code, such as this:
var firstResult = firstOperation(initialArgument);
var secondResult = secondOperation(firstResult);
var finalResult = thirdOperation(secondResult );
alert(finalResult);
The function executed first provides the required data for the function executed later. However, after using our asynchronous calling framework, the same logic must become like this:
firstAsyncOperation(initialArgument).addCallback(function(firstResult) {
secondAsyncOperation(firstResult).addCallback(function(secondResult) {
thirdAsyncOperation(secondResult).addCallback(function(finalResult) {
alert(finalResult);
});
});
});
Chain writing
I think the above code It’s really unsightly, and I hope it can be transformed into jQuery-style chain writing. To do this, we first construct a use case:
Async.go (initialArgument)
.next(firstAsyncOperation)
.next(secondAsyncOperation)
.next(thirdAsyncOperation)
.next(function(finalResult) { alert(finalResult); })
In this use case, we pass in initialization data to go, and then pass in a data processing function after each next. These processing functions process the data in order.
Synchronous coexistence
All the above use cases call asynchronous functions, but it is best for us to be compatible with synchronous functions so that users can use this function without caring about the specific implementation of the function. Function. For this purpose we write another use case like this:
Async. go(0)
.next(function(i) { alert(i); return i 1; })
.next(function(i) {
alert(i);
var operation = new Async.Operation();
setTimeout(function() { operation.yield(i 1); }, 1000);
return operation;
})
.next(function(i ) { alert(i); return i 1; })
.next(function(i) { alert(i); return i; });
In the above use case, we Expect to see a prompt information sequence of 0, 1, 2, 3, with an interval of 1000 milliseconds between 1 and 2.
Asynchronous nature
A chain call is essentially an asynchronous call, so it also returns an Operation instance. This instance naturally also has the fields result, state and completed, and when the entire chain of calls is completed, result is equal to the result returned by the last call, and completed is naturally equal to true.
We can expand the previous use case and get the following use case code:
var chainOperation = Async.go(0)
.next(function(i) { alert(i); return i 1; })
.next(function(i) {
alert (i);
var operation = new Async.Operation();
setTimeout(function() { operation.yield(i 1); }, 1000);
return operation;
})
.next(function(i) { alert(i); return i 1; })
.next(function(i) { alert(i); return i; });
setTiemout(function () { alert(chainOperation.result; }, 2000);
Save the return of the chain call. When the chain call is completed, its result should be consistent with the return of the last operation. In the use case above, that's 3.
Calling Timing
Although we provide a chained calling method, users may not necessarily call in this fixed way, so we still have to consider various possibilities for compatibility with users Usage, for example, use next to add an operation to the call chain asynchronously:
var chainOperation = Async.go(0);
chainOperation.next(function(i) { alert(i); return i 1; });
setTimeout(function() {
chainOperation. next(function(i) {
alert(i);
var operation = new Async.Operation();
setTimeout(function() { operation.yield(i 1); }, 2000);
return operation;
})
}, 1000);
setTimeout(function() {
chainOperation.next(function(i) { alert(i); return i 1; } );
}, 2000);
In this use case, the user adds an operation every 1000 milliseconds, and the second operation takes 2000 milliseconds. In other words, the second operation has not yet returned when the third operation is added. As a robust framework, it must be compatible with such usage.
In addition, we also need to consider that users may want to construct the call chain first and then execute the call chain. At this time, the user will first use the next method to add the operation, and then use the go method to execute it.
var chainOperation = Async
.chain(function( i) { alert(i); return i 1; })
.next(function(i) {
alert(i);
var operation = new Async.Operation();
setTimeout (function() { operation.yield(i 1); }, 2000);
return operation;
})
.go(0)
setTimeout(function() {
chainOperation .next(function(i) { alert(i); return i 1; })
}, 1000);
In the above use case, the user added header synchronization via chain and next One operation and one asynchronous operation, then use go to execute the call chain, and use next to asynchronously append an operation before the call chain is completed. A robust framework should be able to prompt 0, 1, 2 as the user expects in such use cases.
Summary
In response to the demand for chain calls, we have designed so many use cases, including various strange asynchronous calling methods. How to finally achieve such a function?

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Evaluating the cost/performance of commercial support for a Java framework involves the following steps: Determine the required level of assurance and service level agreement (SLA) guarantees. The experience and expertise of the research support team. Consider additional services such as upgrades, troubleshooting, and performance optimization. Weigh business support costs against risk mitigation and increased efficiency.

The lightweight PHP framework improves application performance through small size and low resource consumption. Its features include: small size, fast startup, low memory usage, improved response speed and throughput, and reduced resource consumption. Practical case: SlimFramework creates REST API, only 500KB, high responsiveness and high throughput

Writing clear and comprehensive documentation is crucial for the Golang framework. Best practices include following an established documentation style, such as Google's Go Coding Style Guide. Use a clear organizational structure, including headings, subheadings, and lists, and provide navigation. Provides comprehensive and accurate information, including getting started guides, API references, and concepts. Use code examples to illustrate concepts and usage. Keep documentation updated, track changes and document new features. Provide support and community resources such as GitHub issues and forums. Create practical examples, such as API documentation.

Choose the best Go framework based on application scenarios: consider application type, language features, performance requirements, and ecosystem. Common Go frameworks: Gin (Web application), Echo (Web service), Fiber (high throughput), gorm (ORM), fasthttp (speed). Practical case: building REST API (Fiber) and interacting with the database (gorm). Choose a framework: choose fasthttp for key performance, Gin/Echo for flexible web applications, and gorm for database interaction.

The learning curve of a PHP framework depends on language proficiency, framework complexity, documentation quality, and community support. The learning curve of PHP frameworks is higher when compared to Python frameworks and lower when compared to Ruby frameworks. Compared to Java frameworks, PHP frameworks have a moderate learning curve but a shorter time to get started.

According to benchmarks, for small, high-performance applications, Quarkus (fast startup, low memory) or Micronaut (TechEmpower excellent) are ideal choices. SpringBoot is suitable for large, full-stack applications, but has slightly slower startup times and memory usage.

In Go framework development, common challenges and their solutions are: Error handling: Use the errors package for management, and use middleware to centrally handle errors. Authentication and authorization: Integrate third-party libraries and create custom middleware to check credentials. Concurrency processing: Use goroutines, mutexes, and channels to control resource access. Unit testing: Use gotest packages, mocks, and stubs for isolation, and code coverage tools to ensure sufficiency. Deployment and monitoring: Use Docker containers to package deployments, set up data backups, and track performance and errors with logging and monitoring tools.

When choosing a Go framework, key performance indicators (KPIs) include: response time, throughput, concurrency, and resource usage. By benchmarking and comparing frameworks' KPIs, developers can make informed choices based on application needs, taking into account expected load, performance-critical sections, and resource constraints.
