【发布时间】: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