0

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 ?

Guillaume LUNIK
  • 169
  • 1
  • 2
  • 13

2 Answers2

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)
}
guijob
  • 4,413
  • 3
  • 20
  • 39
0

you have to "chain" your promises like this:

myfunction1().then((value1) => {
  return myfunction2().then((value2) => {
    console.log(value1)
  })
}).catch((err) => {
  console.error(err)
}
messerbill
  • 5,499
  • 1
  • 27
  • 38