【发布时间】:2016-08-09 23:31:00
【问题描述】:
我有许多异步方法要执行,我的程序流程可能会根据每个方法返回而发生很大变化。下面的逻辑就是一个例子。我无法使用 Promises 以易于阅读的方式编写它。你会怎么写呢?
Ps:欢迎更复杂的流程。
Ps2:is_business 是一个预定义的标志,我们在其中说明我们是在编写“商业用户”还是“个人用户”。
begin transaction
update users
if updated
if is_business
update_business
if not updated
insert business
end if
else
delete business
end if
else
if upsert
insert user
if is_business
insert business
end if
end if
end if
commit transaction
【问题讨论】:
-
我认为这是一个公平的问题。所有这些操作都应该是异步的吗?
-
是的@mooiamaduck。实际上我正在做的数据库插入/更新都是异步的。
-
逻辑有问题。
if is_busines { *...* } else { *delete business* }。如果不是业务,您为什么要删除业务。同样,*update business* if not updated *insert business*。您应该更新业务或插入业务。 -
您不需要使用任何库。在 ES7 引入缓解异步和等待之前,您可以使用标准 ES6 承诺/生成器实现简单的
Promise.coroutine()方法,并在生成器函数中处理异步工作流,就好像它是同步的一样。如果我今天晚些时候能找到一些时间,我会试着举个例子。 -
@Redu 了解它的工作原理很好,但我不知道为什么我会自己实现它只是说我做到了,当有像 bluebird 的
Promise.coroutine或co这样的选项时图书馆可用。
标签: javascript node.js promise