Access result of previous promise inside a second

2019-08-23 04:41发布

问题:

This question already has an answer here:

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

I'm using the return pattern to prevent me from making promise ugly cascade. Here is an exemple, I'm calling two function one after the other myfunction1 and myfunction2

myfunction1().then((value1) => {
  return myfunction2()
}).then((value2) => {
  console.log(value1)
}).catch((err) => {
  console.error(err)
})

How can I access value1 inside the then of the seconde function ?

回答1:

You must pass it through your chain. That's why I started using async/await:

try {
    var value1 = await myfunction1();
    var value2 = await myFunction2();
    console.log(value1)
} catch (err) {
    console.error(err)
}


回答2:

you have to "chain" your promises like this:

myfunction1().then((value1) => {
  return myfunction2().then((value2) => {
    console.log(value1)
  })
}).catch((err) => {
  console.error(err)
}