A little question today: how do I get the return value of a JavaScript asynchronous function?
1. Wrong attempt
My initial attempt when I did not enter:
<script>
function getsomething () {
var r = 0;
settimeout (function () {
r = 2;
}, ten);
return r;
}
function Compute () {
var x = getsomething ();
Alert (x * 2);
}
Compute ();
</script>
2. Callback function
The pop-up is not 4, but 0, and then know that this is an asynchronous problem,
To do with the callback technique:
<script>
function getsomething (CB) {
var r = 0;
settimeout (function () {
r = 2;
CB (R);
}, ten);
function compute (x) {
alert (x * 2);
}
Getsomething (compute);
</script>
3.promise
The callback function is a good thing, and it's been writing code for a long time. Encounter asynchronous on the transfer function!! Later I know that there is a promise this thing, specifically to solve the problem caused by the callback function, and learned the promise:
<script>
function getsomething () {
var r = 0;
return new Promise (function (resolve) {
settimeout (function () {
r = 2;
Resolve (R);
},;}
);
function compute (x) {
alert (x * 2);
}
Getsomething (). then (compute);
</script>
Promise still did not give up the callback, but the position of the callback changed.
4.generator
Then I learned generator, knowing that it had the ability to interrupt function execution, and made a new attempt:
<script>
function getsomething () {
var r = 0;
settimeout (function () {
r = 2;
It.next (R);
}, ten);
function *compute (IT) {
var x = yield getsomething ();
Alert (x * 2);
}
var it = compute ();
It.next ();
</script>
Synchronous writing, can realize asynchronous logic, feel tall a lot.
5.promise + Generator
Later heard that promise Plus generator, is the perfect way to asynchronous, quickly use flak to hit mosquitoes (this example, not enough to say the benefits of the two together):
<script>
function getsomething () {
var r = 0;
return new Promise (function (resolve) {
settimeout (function () {
r = 2;
Resolve (R);
},;}
);
function *compute () {
var x = yield getsomething ();
Alert (x * 2);
}
var it = compute ();
It.next (). Value.then (function (value) {
it.next (value);
});
</script>
6.async
Thought this is enough cock, then heard Es7 gave the ultimate solution: Async.
As a teenager who loves to learn, he thinks he can't be left behind:
<script>
function getsomething () {
var r = 0;
return new Promise (function (resolve) {
settimeout (function () {
r = 2;
Resolve (R);
},;}
);
Async function Compute () {
var x = await getsomething ();
Alert (x * 2);
}
Compute ();
</script>
At last there was a sigh of relief.
Postscript:
All of the above examples can be run on the latest chrome. A small example, ordered a few nouns.
Of course, is only "point" only, if can provide the reader to study the relevant knowledge point of a trigger, then old Yao is satisfied.
The above is the old Yiu Dong shoes to share all the content, we hope to understand that JavaScript asynchronous functions can help