apopa
apopa

Reputation: 170

Return multiple values, including a promise

...
var me = 'you';
return aPromise();
}).then(data => {
  // i want me here
})

function aPromise() {
  return new q.Promise((resolve, reject) => {
      resolve(iReturnAnObject());
    }, reject);
});

I want the me variable inside the scope of the then method. If I try something like:

...
var me = 'you';
return [aPromise(), me];
}).then(data => {
  let promise, me;
  [promise, me] = data;
  console.log(promise); //incomplete object
})

The promise variable won't contain the entire object aPromise() should return, it's still pending.

Upvotes: 1

Views: 1891

Answers (3)

Brendan Quinn
Brendan Quinn

Reputation: 170

If I understand your question correctly, you can inject the var into the success callback.

const other = 'other var';
const promise = new Promise(
        function(resolve, reject) {
            window.setTimeout(
                function() {
                    // We fulfill the promise !
                    resolve('response');
                }, 2000);
        }
    );

// or

promise.then(function(other, response) {
  console.log(other, response);
}.bind(null, other))

Can you give more context though? It might be easier to pass the other variable into resolve().

Upvotes: 0

Maxx
Maxx

Reputation: 1748

somePromise.then(() => {
    const me = 'you';
    return aPromise().then(aPromiseData => Promise.resolve({aPromiseData, me}))
}).then(data => {
    const {aPromiseData, me} = data;
})

Upvotes: 0

Pandaiolo
Pandaiolo

Reputation: 11568

You can just nest the promise:

...
var me = 'you';
return aPromise().then(data => {
  // me is here
})

Otherwise, you have to wrap the array of resolved values:

  ...
  var me = 'you';
  return Promise.all([aPromise(), me]);
}).then(data => {
  let [promise, me] = data;
  // use me here
  promise.then(...)
}) 

Upvotes: 1

Related Questions