As async said, pormise object or simple data(such as number or string) can follow by await, when it's simple data, it just as sync, I write the following first program:
let fs = require('fs');
async function readF(){
let data1 = await fs.readFileSync('./file1.txt','utf-8');
console.log(data1);
let data2 = fs.readFileSync('./file2.txt','utf-8');
console.log(data2);
}
readF();
console.log('outter hello');
and the result is :
outter hello
first file
second file
It seems that the readF function is async? why?
and I write a second program, just change the await to the second file reader:
let fs = require('fs');
async function readF(){
let data1 = fs.readFileSync('./file1.txt','utf-8');
console.log(data1);
let data2 = await fs.readFileSync('./file2.txt','utf-8');
console.log(data2);
}
readF();
console.log('outter hello');
this time, the result is:
first file
outter hello
second file
I can't understand this strange amazing result, I hope you can help me.
JavaScript is single-threaded, which means it can only execute one thing at any one time. Asynchronous code executes when all synchronous code is completed.
The syntax of async
and await
is that an operation marked as await
can only occur inside a function marked async
, and it marks the point in the code at which to continue executing when the synchronous code is complete.
In JavaScript versions that don't have these features yet, you can emulate it using setTimeout
with a delay of 0
. setTimeout
executes the callback function asynchronously. If you put all statements after await
inside a setTimeout
block, you can see that the behavior is the same:
function async(){
setTimeout(function() {
console.log("first file");
console.log("second file");
}, 0);
}
async();
console.log('outer hello');
function async(){
console.log("first file");
setTimeout(function() {
console.log("second file");
}, 0);
}
async();
console.log('outer hello');