簡體   English   中英

將值傳遞給下一個Promises參數

[英]Passing value into next Promises argument

基本上,我對Promises感到困惑。 因為,我仍然不熟悉從Callback方法繼續處理異步方法。

所以,我有這樣的代碼

const Search = function(name) { //
  return new Promise((resolve, reject) => { //
    let o = [{
        "name": "Apple",
        "quantity": 10
      },
      {
        "name": "Grape",
        "quantity": 5
      }
    ]
    let result = o.filter((n) => n.name == name)
    if (result.length < 1) {
      reject()
      return
    }
    resolve(result[0])
  })
}

const Buy = function(data, qty) {
  return new Promise((resolve, reject) => {
    let o = {
      name,
      quantity
    } = data
    o.quantity = parseInt(o.quantity) - qty
    if (o.quantity < 0) {
      throw new Error("Oops. Quantity is Empty!")
    }
    resolve(o)
  })
}

const Result = function(test) {
  console.log(test)
}

主要目的是如何在Buy函數的qty參數中輸入值?

我當時正在做這樣的事情,但結果出乎我的意料。 我敢肯定,我的代碼缺少一些內容,但我不知道。

Search("Apple")
  .then(Buy, 4)
  .then(Result)

結果是:

{ name: 'Apple', quantity: NaN }

主要目標是:

{ name: 'Apple', quantity: 6 }

還是謝謝你 :)

Search("Apple")
  .then(function(result){return Buy(result, 4)})
  .then(Result)

你試圖通過Buy直接進入.then ,但功能.then總是被傳遞只有1個說法。 因此,您可以在匿名函數中調用並返回Buy ,在其中您可以根據需要應用任意數量的參數。

您可以利用范圍。

function executeSearch() {
    Search("Apple").then(function (searchResult) {

        // feel free to use the result of the first promise 
        // as input parameters to the second if desired
        const name = searchResult.name;
        const quantity = searchResult.quantity;

        Buy(searchResult, 4).then(Result);

    });
}

這與其他答案類似,但表明您可以通過多種方式使用第一個承諾的結果來執行第二個承諾。

then方法接受一個函數,因此您可以將“ buy”更改為以下內容:

const Buy = function(qty) {
  return function(data){
    return new Promise((resolve, reject) => {
      let o = {
        name,
        quantity
      } = data
      o.quantity = parseInt(o.quantity) - qty
      if (o.quantity < 0) {
        throw new Error("Oops. Quantity is Empty!")
      }
      resolve(o)
    })
  }
}

然后您可以像這樣使用它:

Search("Apple")
  .then(Buy(4))
  .then(Result)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM