繁体   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