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=> <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.
https://stackoverflow.com/questions/65769084/why-does-javascript-acts-different-with-sync-async-in-react-and-node January 18, 2021 at 01:05PM
没有评论:
发表评论