Promise.all忽略未解决的承诺而无法正常工作

时间:2019-02-27 14:30:09

标签: javascript promise

我有此代码

    onRemove = (fileId) => {
        this.setState({ removing: true });
        Promise.all([this.props.onRemove(fileId)])
            .then(() => {
                console.log('I execute after');
                this.setState({ removing: false });
            })
            .catch(() => {
                this.setState({ removing: false });
            });
    }

onRemoveonClick从我的jsx代码中触发,如下所示:

onClick={() => {this.onRemove(fileId);}}

出于简单性原因,我的this.props.onRemove如下所示:

    removeFile = (UUID) => {
        const sleep = milliseconds => new Promise(resolve => setTimeout(resolve, milliseconds));
        return sleep(1500).then(() => {
            console.log('I execute');
        });
    };

运行代码时,我会在控制台中得到它:

I execute after
I execute

我当然认为这是错误的!

在执行Promise.all块中的内容之前,then是否应该等待所有的诺言解决?

我想念的是什么,现在我的头撞在墙上了一段时间。

更新:

我已根据建议添加returnremoveFile,但行为保持不变。

1 个答案:

答案 0 :(得分:1)

您提供的代码似乎工作正常。

class ChildComponent extends React.Component {
  state = {
    removing: false
  }
  
  onRemove = fileId => {
    this.setState({ removing: true });
    Promise.all([this.props.onRemove(fileId)]).then(() => {
      console.log('I execute after');
      this.setState({ removing: false });
    })
      .catch(() => {
        this.setState({ removing: false });
      });
  };

  render() {
    return (
      <button onClick={() => { this.onRemove('fileId');}}>
        Remove File
      </button>
    );
  }
}

const ParentComponent = () => {
  const removeFile = UUID => {
    const sleep = milliseconds => new Promise(resolve => setTimeout(resolve, milliseconds));
      return sleep(1500).then(() => {console.log("I execute");});
  }
  
  return <ChildComponent onRemove={removeFile} />
};

ReactDOM.render(<ParentComponent />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<body>
  <div id='root'></div>
</body>