代码之家  ›  专栏  ›  技术社区  ›  Martin Carre

NodeJS:当发送到promise时,如何检索参数

  •  0
  • Martin Carre  · 技术社区  · 8 年前

    我会尽量做到快速简单。

    function foo(param) {
     return fromPromise(blabla, blabla2, param)
      .then((res) => {
       return res
      }).catch((error) => {
       console.log('Oh snap!', error);
      });
    

    我的意思是,在这种情况下,我把一个返回res放在then中,但你可以把你想要的任何东西放在那里,我只需要“fromPromise”的结果以某种方式包括“param”。

    function fromPromise(blabla, blabla2, param) {
     return rp({
      url: `www.someUrl.com/${blabla2}/${param}
      json: true,
     }).then((data) => {
      return data
     }).catch((error) => {
      console.log('Oh snap!', error);
     });
    

    每个功能都有自己的模块。

    提前感谢!

    2 回复  |  直到 8 年前
        1
  •  2
  •   Jerinaw    8 年前

    如果我理解你的要求,你可以这样做。

    function foo(param) { //This creates a closure and param is available to functions created with in it. 
        return fromPromise(blabla, blabla2, param)
            .then((res) => {
                res.param = param; //param is available through the closeure.
                return res;
            })
            .catch((error) => {
                console.log('Oh snap!');
            });
    }
    

    或者你想从第二个函数开始?

    function fromPromise(blabla, blabla2, param) {//This creates a closure and param is available to functions created with in it.
        return rp({
            url: `www.someUrl.com/${blabla2}/${param}
            json: true
        })
        .then((data) => {
            data.param = param;//param is available through the closeure.
            return data;
        }).catch((error) => {
            console.log('Oh snap!', error);
        });
    }
    
        2
  •  1
  •   Sahan Maldeniya    8 年前

    当链接承诺时,函数只接受一个参数。我们所做的是使用ES6中引入的对象破坏和构造来传播1个以上的参数

    function A(x , y) {
       return new Promise((resolve, reject)->{
           return resolve({x, y}) //NOTE the object construction here
       });
    }
    
    function B() {
       return A(1, 2).then(({x, y})-> { //NOTE object destructio
          console.log(x);
          console.log(y)
       })
    }
    

    More on ES6 object destruction

    推荐文章