Eric Whale
Eric Whale

Reputation: 137

Why does JavaScript acts different with Sync/Async in React and node?

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

Answers (3)

turbopasi
turbopasi

Reputation: 3625

unsplash.get returns a Promise

It 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 Promise

As this is a normal synchronous function, your code only continues once this function is finished, by default.

Upvotes: 3

hgb123
hgb123

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

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

Related Questions