简体   繁体   中英

Passing value into next Promises argument

Basically, i'm so confused with the Promises. Because, I'm still new to moved on from Callback method for handling Asynchronous.

So, i have a code like these

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)
}

The main purpose, how i can input a value into a qty arguments on Buy function?

I was do something like this, but the result is not expected what i want. I'm sure, my code has something missing but i don't know.

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

The result is :

{ name: 'Apple', quantity: NaN }

Main goal is :

{ name: 'Apple', quantity: 6 }

Anyway thanks :)

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

You were trying to pass Buy directly into .then , but the function in .then always gets passed only 1 argument. So you can call and return Buy in an anonymous function, where you can apply yourself as many arguments you want.

You can take advantage of scope.

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);

    });
}

This is similar to the other answer but demonstrates that you can use the result of the first promise in any number of ways to execute the second promise.

The then method accepts a function, so what you can do is change your 'buy' to the following:

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)
    })
  }
}

Then you can use it like:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM