如何在JavaScript中设置函数执行顺序以使用回调函数? [英] How to set function execute order to using callback function in JavaScript?
问题描述
我想处理函数执行顺序以使用回调。其实我正在学习Node.js.由于它的异步,我很难处理过程。无论如何,有3个函数有回调,
I want to handle functions execute order to using callbacks. Actually I'm learning Node.js. Because of its async, It's difficult to me to handle process. Anyway, There are 3 function that has callback,
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
我不明白为什么结果如此。我预计如下:
I don't understand why the result is. I expected below:
First
Second
Third
有什么问题?我怎么能正确地做到这一点?在Node.js中,人们通常使用回调来处理函数执行顺序吗?我觉得这有点复杂。不是吗?
What's problem? How could I do it correctly? In Node.js, Do people usually handle functions excute order by using callbacks? that is little complex I think. Isn't it?
推荐答案
如其他答案所述,
first(second(third));
这不符合你的想法。
我认为你真正打算做的是:
I think what you actually meant to do was this:
first(function(){
second(function(){
third(function(){
// ...
});
});
});
在ES6(节点4+)语法中它将是:
In ES6 (Node 4+) syntax it'll be:
first(() => second(() => third()));
但我更喜欢的是一种使用Promises的方法
But what I prefer is an approach that uses 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();
});
}
这完全摆脱了回调,让人更了解实际的控制流程:
This gets rid of callbacks altogether, and makes more sense of the actual control flow:
first()
.then(second)
.then(third);
使用ES7语法(babel / typescript)它只会变成:
And with the ES7 syntax (babel/typescript) it simply becomes:
async function first(){
console.log("First");
}
// async function second...
// async function third...
await first();
await second();
await third();
这篇关于如何在JavaScript中设置函数执行顺序以使用回调函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!