zoukankan      html  css  js  c++  java
  • 如何在实际项目中使用Promise(入门级)

    你们有没有遇到过这样的情况,ES6看过了,Promise的文字概念都懂,但是我要怎么在项目中去写一个Promise呢?

    那天我就是带着这样的疑问去网上搜了下。最后成功地在项目中应用了Promise,只有实际成功使用一次,才能明白它的前因后果,明白它的用途。

    1.这是一个vue的电商项目-商品详情页

    我写了个方法调库存接口。

    通常情况,异步请求完毕,直接处理结果。但现在我需要在不同的地方调用,对结果进行不同的处理。所以我在getStock方法里返回一个promise,也就是把getStock方法里axios.get异步请求的结果直接返回。

    getStock(region_id, product_id) {
      return new Promise((resolve, reject) => {
        axios.get('/index.php/storage-stock.html', {
          params: {
            area_id: region_id,
            product_id: [product_id]
          }
        }).then(function (res) {
          resolve(res)
        }).catch(function (error) {
          reject(error)
        })
      })
    }

    这里请注意关键点,.then() 里面的 resolve(res)

    2.以下是一个调用的地方:

    this.getStock(REGION_ID, this.product_id).then((res) => {
      if (res.data.data) {
        const data = res.data.data
        if (data.length > 0) {
          this.goodsInfo = data[0]
          this.stock = data[0].stock
          this.stock_total = data[0].stock_total
          this.is_danger = data[0].is_danger
          this.marketable = data[0].marketable
        } else {
          this.stock = 0
        }
      }
    })

    这里.then() 里面的res 就是getStock方法的返回值。

    3.另一个调用的地方:

    this.getStock(region_id, product_id).then((res) => {
      if (res.data.data) {
        const data = res.data.data
        if (data.length > 0) {
          that.stock = data[0].stock
          that.stock_total = data[0].stock_total
        } else {
          that.stock = 0
        }
      }
    })

    这样就可以分别在不同的地方处理一个异步请求的返回值了。

  • 相关阅读:
    P3302 [SDOI2013]森林
    P2542 [AHOI2005] 航线规划
    P5795 [THUSC2015]异或运算
    P3320 [SDOI2015]寻宝游戏
    P1963 [NOI2009] 变换序列
    一月练习日志
    计算几何全家桶
    bzoj1076: [SCOI2008]奖励关(期望dp+状压dp)
    bzoj3450 Easy(概率期望dp)
    Eclipse配置 自动补全功能 快捷键 alt+/
  • 原文地址:https://www.cnblogs.com/cathy1024/p/10213670.html
Copyright © 2011-2022 走看看