了解回调以按所需顺序运行代码

时间:2018-01-15 11:33:27

标签: javascript callback

我正在按照本教程进行操作,直到...

function first(){console.log('first')}
function second(){console.log('second')}

first()
second()

//first
//second

然后:

function first(){
  // Simulate a code delay
  setTimeout( function(){
    console.log(1);
  }, 500 );
}
function second(){
  console.log(2);
}
first();
second();

//2
//1

我得到了所有这些,但我不明白如何实施回调以便记录:

//1
//2
按顺序

我知道它会是这样的:

function first(cb){
  // Simulate a code delay
  setTimeout( function(){
    console.log(1);
    cb()
  }, 500 );
}
但是这会爆发。有人可以帮我看看如何正确使用回调

1 个答案:

答案 0 :(得分:1)

应该是:



function first(cb){  
  setTimeout( function(){
    console.log(1);
    cb();           // <-- calling 'cb' is calling 'second'
  }, 500 );
}

function second() {
  console.log(2);
}

first(second);  // pass 'second' as value of cb
&#13;
&#13;
&#13;

更新:

如果你想使用promises(正如你在评论中提到的那样),它应该是:

&#13;
&#13;
function first() {
    return new Promise(function(resolve) {  // <-- Make the first function returning a promise.
        setTimeout(function() { 
            console.log(1);
            resolve(); 
        }, 500);
    });  
}

function second() {
  console.log(2);
}

first().then(function() {  // <- 'first' returns a promise so you can .then on it
    second();
});
&#13;
&#13;
&#13;