如何解决如何在继续之前等待异步完成 - JS
目的:在一个表单中更新和添加产品,同时调用两个api。
每个 api 都遵循这些步骤:
1- check the local bucketapiversion_file,if it is as the s3 one don't download the file if it is different download file locally and update bucketapiversion_file
then 2- add or edit the file
3- save the file locally (and save in db)
4- upload it to s3
5- update bucketapiversion_file locally (using versionning)
**每个点都是一个异步函数 但是当我调用这些 api 时,您可以在终端中看到该顺序不受尊重here
这两个 api 被调用并同时运行,这使我的代码无法正常运行,我相信。每个 api 同时检查 s3 版本(即使它不应该是相同的!)并同时写入和上传它,即使首先调用网络更新然后更新 as we can see 我怎样才能防止这种情况发生?
解决方法
这里的关键是每一步都是异步的。您必须等待每个步骤完成,因为您需要强制执行顺序并使用每个异步函数的输出。我会尝试勾勒出实现的草图,以便您了解这个想法。
async function doProcess() {
let processInput = {}
let stepOneOutput = await stepOne(processInput)
let shouldEdit = decideBasedOnOutput(stepOneOutput)
if(shouldEdit) {
let stepTwoOutput = await stepTwo(stepOneOutput)
}
[...]
}
async function stepOne(stepOneInput) {
[...]
}
async function stepTwo(stepTwoInput) {
[...]
}
以上代码符合 ES8+,如果你不能使用 ES8+,我建议使用 Promises。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。