【问题标题】:How to wait for two async functions to end?如何等待两个异步函数结束?
【发布时间】:2020-07-22 15:45:48
【问题描述】:

我在 if-else 语句中有 2 个 promise 函数。

if(file_type == "pdf"){
  // Some Promise
  .then(data =>
    result = data;
  )
}
else{
  // Other Promise
  .then(data => 
    result = data
  )
}
// Do something with the data

我想要的是同步的最后一部分不应该在执行承诺之前发生,但我不想在承诺的then 块中重复同步代码。有办法吗?

我尝试的是

async() => { if(file_type == "pdf"){
  await // Some Promise
  .then(data =>
    result = data;
  )
}
else{
  await // Other Promise
  .then(data => 
    result = data
  )
}
}
// Do something with the result

但是这种方法没有奏效。它直接跳过了异步部分。

对不起,如果这是一个非常愚蠢的问题。我在 YouTube 和 StackOverflow 上搜索它,但都是徒劳的。 感谢您的帮助

【问题讨论】:

  • 当你使用await时,你不会使用.then()。你可以这样做:var result = await somePromise();。另外,请确保您正在调用您的 async 函数。
  • @LuketheGeek 如何调用无名异步函数?
  • 定义你的函数并在之后调用它:(async () => { /* do some async stuff here */ })();。注意函数定义后的()。这称为立即调用函数表达式 (IIFE)。有关详细信息,请参阅flaviocopes.com/javascript-iife

标签: javascript node.js reactjs asynchronous


【解决方案1】:

使用条件运算符引用Some PromiseOther Promise,然后对该Promise 调用.then

const prom = file_type == 'pdf' ? somePromise : otherPromise;
prom.then((data) => {
  // Do something with the data
});

确保将所有依赖于异步信息的功能内部.then 回调,而不是外部。不要分配给外部变量。

你也可以把它放到一个命名函数中:

const processData = (data) => {
  // Do something with the data
};
const prom = file_type == 'pdf' ? somePromise : otherPromise;
prom.then(processData);

【讨论】:

  • 是的,但您在这里没有使用await。应该是const data = await (file_type == "pdf" ? somePromise : otherPromise);
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多