Ade Firman Fauzi
Ade Firman Fauzi

Reputation: 377

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

Upvotes: 2

Views: 191

Answers (3)

Joe Lissner
Joe Lissner

Reputation: 2472

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)

Upvotes: 2

TKoL
TKoL

Reputation: 13892

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.

Upvotes: 4

caesay
caesay

Reputation: 17213

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.

Upvotes: 3

Related Questions