代码之家  ›  专栏  ›  技术社区  ›  Jonathan Eustace

我如何将一个承诺与另一个联系起来?

  •  0
  • Jonathan Eustace  · 技术社区  · 9 年前

    我试图在同一个链中使用两个promise库,rp是请求promise,dc是我自己的,检查日期是否正确。

    /*this works fine (checks if date are in correct order)*/
    dc.checkIfDateIsAfter(departure_date,return_date)
    .then(console.log)
    .catch(console.log)
    
    /*this also works fine (makes a post request)*/
    rp(options)
    .then(console.dir)
    .catch(console.error)
    
    /*This works up until the rp call, how do I write this chain?*/
     dc.checkIfDateIsAfter(departure_date,return_date)
    .then(console.log).then(rp(options))
    .then(console.log)
    .catch(console.log);
    
    3 回复  |  直到 9 年前
        1
  •  1
  •   bawjensen    9 年前

    承诺 then 函数通过接受 作用 。在此代码部分中:

    dc.checkIfDateIsAfter(departure_date,return_date)
    .then(console.log)
    .then(rp(options))
    .then(console.log)
    .catch(console.log);
    

    你用第二个做什么 然后 调用正在传递函数 已经用一些参数调用了 ,那么实际上传递给 然后 函数是 后果 rp(options) 。你注意到 console.log 没有常用的括号?这就是为什么。

    解决方法是传入一个函数,其中包含要“绑定”到该函数的数据,但尚未调用该函数。在JavaScript中实现这一点的方法是:

    dc.checkIfDateIsAfter(departure_date,return_date)
    .then(console.log)
    .then(rp.bind(null, options))
    .then(console.log)
    .catch(console.log);
    

    rp.bind()类“保存”了以后调用rp函数时使用的选项。第一个论点的原因是 null 是因为这是用作 this 函数调用内部的变量,我们实际上不需要(希望)。

    另一个修复方法是创建一个新的匿名函数,该函数的特定角色是调用 rp 具有 options :

    dc.checkIfDateIsAfter(departure_date,return_date)
    .then(console.log)
    .then(function() { return rp(options); })
    .then(console.log)
    .catch(console.log);
    
        2
  •  1
  •   fuyushimoya    9 年前

    Promise.then 预料 function as参数,否则忽略它,as rp(options); 似乎又回来了 Promise ,它的解析值不受关注。

    您应该使用函数包装它,并返回调用 rp(options) .

    还值得注意的是 console.log 回报 undefined ,如果您希望从 checkIfDateIsAfter ,您还应该包装它,并返回结果,这样该值就可以传递给next。

    dc.checkIfDateIsAfter(departure_date,return_date)
    .then(function(res) {
      console.log(res);
      // Pass the value which would be logged to next chain
      // if it'll be used later.
      return res;
    }).then(function(res) {
      // if the rp has anything to do with the value.
      rp(options);
    })
    .then(console.log)
    .catch(console.log);
    
        3
  •  1
  •   vodolaz095    9 年前

    尝试

     dc.checkIfDateIsAfter(departure_date,return_date)
      .then(console.log)
      .then(function(){ return rp(options);})
      .then(console.log)
      .catch(console.log);