Reputation: 137
This is code from my React project.
If you read the onSearchSubmit function written(line: 3) + "unsplash" is axios.create()
call
class App extends React.Component {
state = { images: [] };
onSearchSubmit = async term => {
const response = await unsplash.get('/search/photos', {
params: { query: term }
});
this.setState({ images: response.data.results });
};
render() {
return (
<div className='ui container' style={{ marginTop: '10px' }}>
<SearchBar onSubmit={this.onSearchSubmit} />
<ImageList images={this.state.images} />
</div>
);
}
}
If I hadn't used async, I would get an error message because a response variable is undefined(yet, due to time-consuming HTTP request)
Therefore, the code "doesn't wait" for something to finish, rather it moves on with an undefined variable in React
But in node js it's different.
const fs = require('fs');
const input = fs.readFileSync('input.txt', 'utf-8');
console.log(input);
This is a simple code which "waits" for the second line, and when it's over, the next line executes.
What's the difference? Those two are both JS codes but acts differently for me.
Upvotes: 1
Views: 129
Reputation: 3625
unsplash.get
returns a PromiseIt returns a promise which needs to be resolved. As long it's not being resolved, it returns nothing, therefore response will be undefined
. To resolve the Promise you can either use await
inside an async
function, like you did, to tell the code to wait for
a result:
const response = await unsplash.get();
or you can use classic .then
unsplash.get()
.then((response) => {
// ... continue here
})
.catch((error) => {
// ... error handler
});
readFileSync()
is a synchronous operation, does not return a PromiseAs this is a normal synchronous function, your code only continues once this function is finished, by default.
Upvotes: 3
Reputation: 14891
According to this section, it cited that
The synchronous form blocks the Node.js event loop and further JavaScript execution until the operation is complete
So readFileSync()
is a synchronous method that would wait for the operation to finish before moving on another operation. Even in its doc shows that
Returns: string | Buffer
FYI, readFile
also has a version that return promise
Upvotes: 0
Reputation: 5734
The axios .get()
function is asynchronous so you must use await
in order to have the response
variable available, while fs.readFileSync()
is a syncronous function (it's right in the name, the asyncrhonous version is fs.readFile()
) so the code waits for it to complete.
Upvotes: 0