在 Node.js 中进行一系列异步操作的好方法是什么?这是针对脚本类型的应用程序,一个应该从命令行运行然后完成工作的应用程序,它不在应该位于后台并同时处理多个不同事物的服务器的上下文中。
我知道 Promises/A+ aka Thenables,但语法不太好:
do_some_stuff().then(
function() {
do_some_other_stuff().then(
function() {
do_the_last_stuff().then(
function() {
// we are done with everything!
}
)
}
)
}
);
当我们有更多的操作时,缩进会使它看起来很丑。
我喜欢 jasmine 的处理方式,异步操作通过一个函数传递,完成后应该调用该函数。基于这个想法,我创建了一个我称之为 AsyncSequence 的东西。 AsyncSequence 运行一系列操作,每个操作都传递一个 done
函数,该函数应在完成时调用。使用 AsyncSequence 上面的代码看起来像:
AsyncSequence.run(
function(done) {
do_some_stuff().then(done);
},
function(done) {
do_some_other_stuff().then(done);
},
function(done) {
do_the_last_stuff().then(done);
},
function() {
// we are done with everything!
}
);
这行得通而且我认为它看起来更好,但我想知道是否有更“标准”的方法来做到这一点?当经验丰富的 Node.js 程序员看到这个时,是否会想到类似于我的 AsyncSequence 的内容?或者不完全相似但可以用于相同目的的东西?
最佳答案
有了 Promises/A+,then
可以被链接起来,使你的第一个例子:
do_some_stuff()
.then(do_some_other_stuff)
.then(do_the_last_stuff)
.then(function() {
// we are done with everything!
});
将 promise 视为 future 值(value)的容器,then
将 future 值转换为另一个值(有点像 [].map
).但是,如果您传递给 then
的函数返回另一个 promise,它就会被解包。更具体的例子:
getPostData(req).then(function(data) {
return createNewUser(data);
}).then(function(user) {
return JSON.stringify(user);
}).then(function(json) {
return successResponse(json);
}).then(function(body) {
res.end(body);
});
此示例使用显式函数参数使流程更加明显。 createNewUser
返回一个代表保存到数据库中的用户对象的 promise ,而 JSON.stringify
当然只返回一个字符串。 Promises/A+ 可以处理和链接这两种返回值。
关于javascript - 在node.js中做一系列的异步操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25544823/