如何在实际项目中使用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
    }
  }
})

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

扫描二维码关注公众号,回复: 4761394 查看本文章

猜你喜欢

转载自www.cnblogs.com/basic0001/p/10213670.html