1. 程式人生 > >如何在實際專案中使用Promise(入門級)

如何在實際專案中使用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
    }
  }
})

這樣就可以分別在不同的地方處理一個非同步請求的返回值了。