【问题标题】:Why does JavaScript acts different with Sync/Async in React and node?为什么 JavaScript 在 React 和 node 中与 Sync/Async 的行为不同?
【发布时间】:2021-04-22 10:18:56
【问题描述】:

这是我的 React 项目中的代码。

如果您阅读 onSearchSubmit function written(line: 3) + "unsplash" is axios.create() 电话

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>
        );
    }
}

如果我没有使用异步,我会收到一条错误消息,因为响应变量未定义(但是,由于耗时的 HTTP 请求)

因此,代码 “不等” 为了完成某些事情,而是在 React 中使用未定义的变量继续前进

但在 node js 中就不同了。

const fs = require('fs');
const input = fs.readFileSync('input.txt', 'utf-8');
console.log(input);

这是一个简单的代码 “等待” 第二行,当它结束时,执行下一行。

有什么区别?这两个都是 JS 代码,但对我来说作用不同。

【问题讨论】:

    标签: javascript node.js reactjs async-await


    【解决方案1】:

    unsplash.get 返回一个 Promise

    它返回一个需要解决的承诺。只要它没有被解决,它就什么也不返回,因此响应将是undefined。要解决 Promise,您可以像您一样在 async 函数中使用 await,将结果告诉 wait for

    const response = await unsplash.get();
    

    或者你可以使用经典的.then

    unsplash.get()
    .then((response) => {
      // ... continue here
    })
    .catch((error) => {
      // ... error handler
    });
    

    readFileSync() 是同步操作,不返回 Promise

    由于这是一个普通的同步函数,默认情况下,您的代码只会在此函数完成后继续执行。

    【讨论】:

      【解决方案2】:

      axios .get() 函数是异步的,所以你必须使用await 才能使response 变量可用,而fs.readFileSync() 是一个同步函数(顾名思义,异步版本是@987654325 @) 所以代码等待它完成。

      【讨论】:

        【解决方案3】:

        根据this section,它引用了那个

        同步表单阻止 Node.js 事件循环和进一步的 JavaScript 执行,直到操作完成

        所以readFileSync() 是一种同步方法,它会等待操作完成,然后再进行另一个操作。即使在其doc 中也表明

        返回:字符串 |缓冲区

        仅供参考,readFile 也有一个 version that return promise

        【讨论】:

          猜你喜欢
          • 2016-07-05
          • 1970-01-01
          • 2023-03-11
          • 2020-11-19
          • 2015-09-24
          • 1970-01-01
          • 2021-10-31
          相关资源
          最近更新 更多