H5 used in the project do mixed programming, but still the android set of logic is required between a lot of callbacks and asynchronous thread, involving asynchronous and synchronous processing. The actual development uses a lot of callbacks, make the code less readable, scalable reduced. For example, when the interface is started, you need to get the data in the network, there is a temporary cache, multiple asynchronous threads to use this data.
Here again H5 learn about asynchronous programming, optimizing the code logic
H5 asynchronous programming methods, the article says quite detailed
javascript asynchronous programming in 5 ways
I am using async / awai + promis to solve the asynchronous transfer synchronization problems on promise, this article speaks more clearly
Asynchronous programming JS (promise, deferred object)
Understand the promise, synchronize asynchronous write
Chinese documents
demo1
function testPromise() {
console.log(">>>>>11111");
testResult();
console.log(">>>>>22222");
}
function getPromise(num) {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log(">>>>>55555");
resolve(2 * num)
console.log(">>>>>666666");
}, 200);
} )
}
async function testResult() {
console.log(">>>>>33333");
let result = await getPromise(1);
console.log(">>>>>44444>>result:"+result);
}
Print results
1->3->2->5->6->4
testPromise testResult method is asynchronous, the main thread is not blocked
testResult method getPromise methods await identification method is synchronous, blocking the main thread to wait resolve method returns the results came back to continue.
Although the method returns getPromise new Promise, but actually resolve the value of the return.
demo2
function testPromise() {
console.log(">>>>>11111");
var a = testResult();
a.then(function (res) {
console.log(">>>>>77777+res:" + res);
})
console.log(">>>>>22222");
}
function getPromise(num) {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log(">>>>>55555");
resolve(2 * num)
console.log(">>>>>666666");
}, 200);
} )
}
async function testResult() {
console.log(">>>>>33333");
let result = await getPromise(1);
console.log(">>>>>44444>>result:"+result);
return result
}
Print Results:
demo2, the method testResult value back to the Promise objects, the method is performed after testPromise .then acquisition, so can be returned to a value or
2 ① printing prints, printed last 7, testPromise testResult method is asynchronous, the main thread is not blocked
Detailed test also can refer to this article
https://blog.csdn.net/qq_32899575/article/details/83107587