ewo*_*wok 19 javascript promise
我有一个条件语句,我需要执行两个操作之一,然后在解决了哪个操作后继续.所以我的代码目前看起来如下:
if (shoud_do_thing_a) { //should_do_thing_a is just a variable that determines which function to call. it is not a promise
do_thing_a()
} else {
do_thing_b()
}
// more code
Run Code Online (Sandbox Code Playgroud)
问题是,这两个do_thing_a和do_thing_b回用,直到两者被执行已经解决了,我不能继续前进.我想出解决这个问题的最好方法是这样的:
var more_code = function () {
// more code
}
if (shoud_do_thing_a) {
do_thing_a().then(more_code)
} else {
do_thing_b().then(more_code)
}
Run Code Online (Sandbox Code Playgroud)
我不喜欢这种结构.这很难理解,因为你需要跳转才能找到more_code定义的位置(想象一下我在几个地方都有这种类型的控制流),而不是简单地继续阅读.
有没有更好的方法来处理这种类型的东西在JavaScript中?
CRi*_*ice 17
或者:
var more_code = function () {
// more code
}
var do_thing;
if (shoud_do_thing_a) {
do_thing = do_thing_a()
} else {
do_thing = do_thing_b()
}
do_thing.then(more_code)
Run Code Online (Sandbox Code Playgroud)
或者,如果您可以使用async/await
async function someFunc() {
var more_code = function () {
// more code
}
if (shoud_do_thing_a) {
await do_thing_a()
} else {
await do_thing_b()
}
more_code()
}
Run Code Online (Sandbox Code Playgroud)
如果您对原始的Promises感到困惑并且无法使用async/await(通常应该没有问题,例如babel / typescript等),那么与将promise存储在变量中相比,以下内容要优雅一些:
function something() {
return Promise.resolve()
.then(() => {
if (should_do_thing_a) {
return do_thing_a();
}
else if (should_do_thing_b) {
return do_thing_b();
}
})
.then(some_more_code);
}
Run Code Online (Sandbox Code Playgroud)
请注意,当您开始使用Promises时,您的函数应始终返回其他函数可以使用的Promise。留下没有任何处理方式的异步操作意味着不好的事情,尤其是在错误处理方面。
从更一般的意义上讲,这意味着当您使用Promises时,您的更多代码将“提升”为被执行并作为Promises返回。
| 归档时间: |
|
| 查看次数: |
22205 次 |
| 最近记录: |