试图复制回调地狱

时间:2018-10-17 17:57:42

标签: javascript callback

我一直在尝试了解回调地狱,并试图复制然后将其更改为Promise。这是我的代码,在执行时说cb不是函数

我在这里想念的东西。

var t = addTwo(function(a, b) {
  console.log(a * b);
  divideTwo(function() {
    console.log("arshita");
  })
})

function addTwo(cb) {
  cb(3, 4);
}

function divideTwo(cb1) {

}
addTwo();

1 个答案:

答案 0 :(得分:0)

您的代码有误

var t = addTwo(function(a, b) {
  console.log(a * b);
  divideTwo(function() {
    console.log("arshita");
  })
})

function addTwo(cb) {
  cb(3, 4);
}

function divideTwo(cb1) {

}
addTwo((a, b) => a + b); // <----- Here you passed nothing, though `addTwo` 
// expected a callback. I wrote an example callback that sums `a` and `b`

更新

如果您想看看回调地狱是什么样子,那么请看一下(一个简单的,仅三级的回调地狱):

function init(msg, cb) {
  alert(msg)
  cb()
}

function running(msg, cb) {
  alert(msg)
  cb()
}

function finish(msg) {
  alert(msg)
}

// The below code may not be considered as "callback hell" yet, but add few more iterations and it definitely will become a hell
init('program started!', function() {
  running('program is running', function() {
    finish('program shut downs')
  })
})