使用Promise避免回调地狱

提出问题

在前端开发过程中,经常碰到以下情况:调用A方法获取B方法的参数a,调用B方法获取C方法的参数b,最终调用C服方法获取要在Web页面显示的真实数据,如下:

    // 回调地狱
    componentDidMount() {
        getStudentInfo('zhangyun').then(studentInfo => {
            console.log(studentInfo);
            getClassInfo(studentInfo.classId).then(classInfo => {
                console.log(classInfo);
                getSchoolInfo(classInfo.schoolId).then(schoolInfo => {
                    console.log(schoolInfo);
                    this.setState({
                        schoolInfo,
                    })
                })
            })
        })
    }

上述代码通过如下步骤最终获取schoolInfo信息:

  • 调用getStudentInfo方法获取classId,即getClassInfo方法参数
  • 调用getClassInfo方法获取schoolId,即getSchoolInfo方法参数
  • 调用getSchoolInfo方法获取最终需要显示的schoolInfo信息

当回调函数数量较少的时候还好处理,当数量越来越多,使用上面的方法会导致多层回调方法嵌套,也就是所谓的”回调地狱“,ES6提供了Promise对象来避免以上情况的产生。


Promise简介

Promise通俗来说就是1个对象,里面存放将来某个未来才会结束的事件(通常是1个异步操作的结果),分为Pending(进行中)、Fulfilled(已成功)和Rejected(已失败)3种状态,Promise对象的状态改变只有两种可能:

  • Pending变成Fulfilled
  • Pending变成Rejected

为了避免回调地狱,可以使用Promise将异步操作以同步操作的流程表达出来。


Promise基本用法

创建1个Promise实例:

const promise = new Promise(function(resolve, reject) {
  // ... some code

  if (/* 异步操作成功 */){
  // value表示异步操作的结果,返回value给Promise对象
    resolve(value);
  } else {
    reject(error);
  }
});

其中resolvereject两个参数为JavaScript提供的方法,其作用为:

  • 改变Promise对象状态
  • 传递结果:resolved或者rejected

Promise实例生成后,可以用then方法分别指定resolved状态和rejected状态的回调函数:

promise.then(function(value) {
  // 参数1 success
}, function(error) {
  // 参数2 failure
});

then方法可以接受2个回调函数作为参数,其中:

  • 参数1 <==> resolved回调函数
  • 参数2 <==> rejected回调函数(可省略)

解决问题

Promise解决回调地狱的方法就是将第1个回调函数返回的结果作为参数传入第2个回调函数。

话不多说,直接上代码:

import React, {Fragment, PureComponent} from 'react';
import {
    getStudentInfo,
    getClassInfo,
    getSchoolInfo
} from '@/services/es6Service'


class App extends PureComponent {

    state = {
        schoolInfo: {
            schoolId: '',
            schoolName: '',
            city: ''
        }
    };

    componentDidMount() {
       // 避免回调地狱
        this.asyncProcessStudent('zhangyun')
            .then(this.asyncProcessClass)
            .then(this.asyncProcessSchool)
            .then(data => {
                console.log(`第4步:输出schoolInfo`)
                console.log(data);
            })
    }

    // 创建第1个返回Promise对象的函数,9s后触发getStudentInfo方法
    asyncProcessStudent = studentName => {
        console.log(`第1步:输出studentName`)
        return new Promise(resolve => {
            // resolve(getStudentInfo(studentName));
            setTimeout(() => resolve(getStudentInfo(studentName)), 9000);
        })
    }
    
    // 创建第2个返回Promise对象的函数,4s后触发getClassInfo方法
    asyncProcessClass = studentInfo => {
        console.log(`第2步:输出studentInfo`)
        return new Promise(resolve => {
            // resolve(getClassInfo(studentInfo.classId));
            setTimeout(() => resolve(getClassInfo(studentInfo.classId)), 4000);
        })
    }

    // 创建第3个返回Promise对象的函数,1s后触发getSchoolInfo方法
    asyncProcessSchool = classInfo => {
        console.log(`第3步:输出classInfo`)
        return new Promise(resolve => {
            // resolve(getSchoolInfo(classInfo.schoolId));
            setTimeout(() => resolve(getSchoolInfo(classInfo.schoolId)), 1000);
        })
    }


    render() {
        const {schoolInfo} = this.state;

        return (
            <div>
                <h1>使用Promise避免回调地狱</h1>
                <div>
                    {schoolInfo.schoolName}
                </div>
            </div>
        );
    }
}

export default App;

关键看如下代码:虽然asyncProcessStudent触发时间是9s后,asyncProcessClassasyncProcessSchool是4s和1s,但是由于asyncProcessStudentresolved状态决定了then中的方法,所以程序会同步执行。

 this.asyncProcessStudent('zhangyun')
            .then(this.asyncProcessClass)
            .then(this.asyncProcessSchool)
            .then(data => {
                console.log(data);
            })

输出结果如下:
在这里插入图片描述


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Promise 是一种用于处理异步操作的对象,它可以有效地解决回调地狱问题。回调地狱是指当多个异步操作依赖于前一个操作的结果时,嵌套的回调函数会导致代码难以理解和维护。 通过使用 Promise,我们可以将异步操作的结果链接在一起,形成一个链式调用。Promise 提供了两个特殊的方法:`then` 和 `catch`。 使用 `then` 方法,我们可以在前一个操作完成后执行下一个操作,并将结果传递给下一个操作。这样可以避免嵌套的回调函数。 使用 `catch` 方法,我们可以捕捉链式调用中出现的任何错误,并进行相应的处理。 下面是一个使用 Promise 解决回调地狱问题的示例代码: ```javascript function asyncOperation1() { return new Promise((resolve, reject) => { // 异步操作1 // 在操作完成后调用 resolve 或 reject }); } function asyncOperation2() { return new Promise((resolve, reject) => { // 异步操作2 // 在操作完成后调用 resolve 或 reject }); } function asyncOperation3() { return new Promise((resolve, reject) => { // 异步操作3 // 在操作完成后调用 resolve 或 reject }); } asyncOperation1() .then(result1 => { // 处理异步操作1的结果 return asyncOperation2(); }) .then(result2 => { // 处理异步操作2的结果 return asyncOperation3(); }) .then(result3 => { // 处理异步操作3的结果 }) .catch(error => { // 处理错误 }); ``` 在上述示例中,每个异步操作返回一个 Promise 对象,并在操作完成后调用 resolve 或 reject。通过使用 `then` 方法,我们将每个操作链接在一起,形成一个链式调用。如果任何操作失败,会自动跳转到 `catch` 方法进行错误处理。 使用 Promise 可以让异步代码更易于理解和维护,避免回调地狱问题的出现。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值