稍后在链

时间:2016-09-26 10:52:40

标签: javascript node.js promise bluebird q

我已经保证第一个链中的响应应该在链中(4和6)中使用的链,我使用一些全局变量来处理它,但这不是正确的方法,有有希望实现这一目标的更好方法是什么?

这是该问题的一些例证......

var step1 = (ms) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      log("This is step 1");
      resolve(20);
    }, ms);
  })
}
var step2 = (ms) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      log("This is step 2");
      resolve();
    }, ms);
  })
};
var step3 = (ms) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      log("This is step 3");
      resolve();
    }, ms);
  })
};

var step4 = (ms) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      log("Step 4, run : " + ms );
      resolve();
    }, ms);
  })
};


var globalVar = null;

//Promise chain
step1(500)
  .then((res) => {
     //Here I keep the response in global variable to use later on
     globalVar = res;
    log(res);
    return step2(300);
  }).then(() => {
    return step3(200);
  }).then(() =>{
   //Here I need to use the res from the first promise
    var lclvar = globalVar +200 ;
    return step4(lclvar);
  }).catch((err) => {
  log(err);
});

我发现了这个但是在这种情况下这没有帮助(至少无法处理它)

How do I access previous promise results in a .then() chain?

2 个答案:

答案 0 :(得分:1)

您可以将step2step3等调用嵌套在第一个处理程序中,然后res可供所有人使用

step1(500).then((res) => {
  log(res);
  return step2(300)
    .then(() => step3(200))
    .then(() => step4(res + 200));
}).catch((err) => {
  log(err);
});

答案 1 :(得分:0)

如果你真的想把这个字串起来。这个想法是沿途的一个公共汽车参数。它是在第一个承诺中创造的一个闭合。

您可以运行此代码:

log=console.log
var step1 = (ms) => {
var Buss={p1:20};   
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      log("This is step 1");
      resolve(Buss);
    }, ms);
  })
}
var step2 = (ms,bus) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      log("This is step 2");
      resolve(bus);
    }, ms);
  })
};
var step3 = (ms,bus) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      log("This is step 3");
      resolve(bus);
    }, ms);
  })
};

var step4 = (bus) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      log("Step 4, run : " + bus.p1 );
      log("bus arrives:",bus);
      resolve(bus);
    }, bus.p1);
  })
};




//Promise chain
step1(500)
  .then((res) => {
     //Here I keep the response in global variable to use later on
     //globalVar = res;
    log(res);
    return step2(300,res);
  }).then((res) => {
    return step3(200,res);
  }).then((res) =>{
   //Here I need to use the res from the first promise
    //var lclvar = globalVar +200 ;
    res.p1+=200;
    return step4(res);
  }).catch((err) => {
  log(err);
});