我想处理函数执行顺序以使用回调。实际上我正在学习 Node.js。由于它的异步,我很难处理流程。不管怎样,有 3 个函数有回调,
function first(callback){
console.log("First");
callback;
}
function second(callback){
console.log("Second");
callback;
}
function third(callback){
console.log("Third");
}
// Let's run it!
first(second(third));
// result
Second
First
我不明白为什么会这样。我预计如下:
First
Second
Third
有什么问题?我怎样才能正确地做到这一点?在 Node.js 中,人们通常使用回调来处理函数执行顺序吗?我认为这有点复杂。不是吗?
最佳答案
如其他答案中所述,
first(second(third));
这并不像您想象的那样。
我想你真正想做的是:
first(function(){
second(function(){
third(function(){
// ...
});
});
});
在 ES6(Node 4+)语法中它将是:
first(() => second(() => third()));
但我更喜欢使用 Promises 的方法
function first(){
return new Promise(function(resolve, reject){
console.log("First");
resolve();
});
}
function second(){
return new Promise(function(resolve, reject){
console.log("Second");
resolve();
});
}
function third(){
return new Promise(function(resolve, reject){
console.log("Third");
resolve();
});
}
这完全摆脱了回调,并使实际控制流更有意义:
first()
.then(second)
.then(third);
<支持> checkout this article on promises
使用 ES7 语法(babel/typescript)它就变成了:
async function first(){
console.log("First");
}
// async function second...
// async function third...
await first();
await second();
await third();
关于javascript - 如何在 JavaScript 中设置函数执行顺序以使用回调函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34556674/