Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Promises, how to pass variable into .then function

Hello this is a question to help me understand how Promises .then returns work. The question is: how can I scoped variables to the second .then chained function?

Here is a jsbin http://jsbin.com/xacuna/edit?js,output

I can access the global variables, and pass in the scoped variables to the first then, but not after.

  let innerReturnFunction = (res, myName) => {
    /* this works */
    console.log(`hi from inner name: ${myName}`)
    return res
  }

 let getInnerFuncVariable = () => {
   var myName = 'arturo'

   return fetch('https://httpbin.org/get')
    .then(function (res) {
      myName = 'Bob'
      return innerReturnFunction(res, myName);
    })
    .then(function (res, myName) {
      /* doesn't work, how can I access myName */
      console.log(`in first then ${res.url}, ${myName}`)
    });
 }

getInnerFuncVariable().then(function(res, myName) {
  /* how can I access myName */
  console.log(`last called ${myName}`)
})
like image 289
ArturoRomero Avatar asked Feb 26 '17 03:02

ArturoRomero


People also ask

Does .then wait for Promise?

You can use the async/await syntax or call the . then() method on a promise to wait for it to resolve. Inside of functions marked with the async keyword, you can use await to wait for the promises to resolve before continuing to the next line of the function.

What is .then in Promise?

The then() method returns a Promise . It takes up to two arguments: callback functions for the fulfilled and rejected cases of the Promise .

How do you get variables from promises?

Define an async function. Use the await operator to await the promise. Assign the result of using the await operator to a variable.

How do you pass a function in Promise?

The constructor syntax for a promise object is: let promise = new Promise(function(resolve, reject) { // executor (the producing code, "singer") }); The function passed to new Promise is called the executor.


1 Answers

as you are using ES2015 - easy solution uses object Shorthand property names and Object destructuring

let innerReturnFunction = ({res, myName}) => {
    /* this works */
    console.log(`hi from inner name: ${myName}`);
    return {res, myName}; // return an object
}

let getInnerFuncVariable = () => {
    var myName = 'arturo';

    return fetch('https://httpbin.org/get')
        .then(function(res) {
            myName = 'Bob'
            return innerReturnFunction({res, myName});
        })
        .then(function({res, myName}) {
            console.log(`in first then ${res.url}, ${myName}`);
            return {res, myName};// ADD THIS!!
        });
}

getInnerFuncVariable().then(function({res, myName}) {
    console.log(`last called ${myName}`)
})
like image 84
Jaromanda X Avatar answered Oct 20 '22 01:10

Jaromanda X