gpt4 book ai didi

javascript - Promise.all 未按预期工作,忽略 Unresolved promise

转载 作者:行者123 更新时间:2023-12-03 00:07:14 25 4
gpt4 key购买 nike

我有这个代码

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

onRemove 由我的 jsx 代码中的 onClick 触发,如下所示:

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 不是应该等待所有 Promise 解析后再执行 then block 中的内容吗?

我错过了什么,已经用头撞墙有一段时间了。

更新:

我按照建议的注释将 return 添加到 removeFile,但行为保持不变。

最佳答案

您提供的代码似乎运行良好。

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>

关于javascript - Promise.all 未按预期工作,忽略 Unresolved promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54907744/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com