如何等待两个异步功能结束?

时间:2020-04-09 22:11:04

标签: javascript node.js reactjs asynchronous

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

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

我想要的是同步的最后一部分不应该在执行Promise之前发生,但是我不想在Promise的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上进行搜索,但都没有用。 感谢您的帮助

1 个答案:

答案 0 :(得分: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);