zoukankan      html  css  js  c++  java
  • NodeJS回调地狱

    NodeJS回调地狱

    一.为什么要写这篇文章

      前段时间和朋友做一个小程序,在很多地方如果用户没有登录,因为小程序的升级,不能直接通过现有的API来获取用户的信息,必须得通过点击按钮的方式,首先获取用户的信息后,进入回调方法,通过switchTab到达登录页面,登录成功后在回到之前的页面。整个逻辑非常的简单,代码实现起来也简单,但是在嵌套上真心恶心到我了。这让我不禁的想到了NodeJS,至于为什么想到NodeJS,你品,你用心品。这个问题,在行业内,大家都把他叫做“回调地狱”。为什么会产生回调地狱呢?因为NodeJS推崇异步编程,那么恰恰是异步编程就容易导致“回调地狱”。

                                                                                                               

    二.案例演示

           现假设这样一个场景,一个程序员去面试,需要经过三轮面试,第二、三轮面试必须要拿到上轮面试通过后的结果才能进行下场面试,而每场面试需要等待一段时间后才给回复,下面通过代码来模拟一下这个场景:

    // 面试
    function interview(callback) {
        setTimeout(() => {
            //模拟出当前面试, 有60%通过的概率
            if(Math.random() <= 0.6) {
                callback(null, 'success')
            }else {
                callback(new Error('error'))
            }
        }, 100)
    }
    
    // 第一轮面试
    interview((e) => {
        if(e) {
            return console.log('fail in 1st round');    
        }
    
        // 第一轮面试通过
        console.log('success in 1th round');
        
        //第二轮面试
        interview((e) => {
            if(e) {
                return console.log('fail in 2nd round');    
            }
            //第二轮面试通过
            console.log('success in 2nd round');
    
            //第三轮面试
            interview(e => {
                if(e) {
                    return console.log('fail in 3rd round');    
                }
                console.log('success');
            })
        })
    })

    三.怎么解决回调地狱?

      那么如何解决回调地狱呢?可以使用Promise、async的方式,这将是在下一篇文章来讲解的。

  • 相关阅读:
    [Everyday Mathematics]20150226
    [Everyday Mathematics]20150225
    [Everyday Mathematics]20150224
    [Everyday Mathematics]20150223
    [Everyday Mathematics]20150222
    [Everyday Mathematics]20150221
    [Everyday Mathematics]20150220
    [Everyday Mathematics]20150219
    [Everyday Mathematics]20150218
    [Everyday Mathematic]20150217
  • 原文地址:https://www.cnblogs.com/miller-zou/p/12324920.html
Copyright © 2011-2022 走看看