有没有办法打破深层嵌套的异步调用?

时间:2017-05-10 04:04:28

标签: javascript asynchronous

我的代码中有以下模式。

function serverGet(callback) {
   return callback("this is the real data");
}

function getData(callback) {
   var c1= true, c2, c3, c4; //c1 set to true as illustration to make snippet run
   if (c1) {
      serverGet(function(data) {
    	  console.log(data);
          return callback(data);  //line 10
      })
    } else {
      //other conditions
      if (c2) {
        //....
      } else {
          if (c3) {
            //....
          } else {
              if (c4) {
                // ....
              } else {
                  // ....
                }
}

function main() {
  getData(function(data) {
    console.log("Finally, the data is: "+data);
  });
}

main();

第10行是否有办法返回main以避免所有if / else阻塞和深度缩进?

1 个答案:

答案 0 :(得分:-1)

Promise只是回调的语法糖。您可以采用与承诺相同的方式进行此操作。

第10行抛出异常并且 a)让它在所有回调中冒泡,这样你就可以在任何地方尝试/ catch块 b)在顶级回调中捕获它

a)更好,因为你可以在各个层面进行必要的清理

相关问题