0

I have two promises that I am resolving with promise.all:

var mictest1 = new Promise((resolve, reject) => {
  resolve(true);
});
var mictest2 = new Promise((resolve, reject) => {
  resolve(true);
});

Promise.all([mictest1, mictest2]).then(data => {
  console.log("test passed: " + data);
})

I would like to put the promises mictest1 and mictest2 into a function called mictest() so it does the following:

mictest();

Promise.all([mictest1, mictest2]).then(data => {
  console.log("test passed: " + data);
})

In this way I can call the function at will, and when the promises get complicated, i don't have that block of text in front of promise.all

1
  • so, you want mictest to populate two global variables, mictest1 and mictest2, with promises? why? Commented Feb 24, 2020 at 2:02

3 Answers 3

1

Maybe you're looking for the mictest function to return the Promise.all?

const mictest = () => {
  var mictest1 = new Promise((resolve, reject) => {
    resolve(true);
  });
  var mictest2 = new Promise((resolve, reject) => {
    resolve(true);
  });
  return Promise.all([mictest1, mictest2]);
};


mictest().then((data) => {
  console.log('test passed:', data);
});

Sign up to request clarification or add additional context in comments.

Comments

1

I think you are looking for a function that returns the promise:

function mictest() {
  return new Promise((resolve, reject) => {
    resolve(true);
  });
}

You'd use it like

var mictest1 = mictest();
var mictest2 = mictest();
Promise.all([mictest1, mictest2]).then(data => {
  console.log("test passed: " + data);
})

or simply

Promise.all([mictest(), mictest()]).then(data => {
  console.log("test passed: " + data);
})

Comments

1

Not quite the way you imagined it but you can get very close:

let promises = mictest();

Promise.all(promises).then(data => {
  console.log("test passed: " + data);
})

That's just changing two lines of your imagined code. The implementation is simple:

function mictest () {
  return [
    new Promise((resolve, reject) => {
      resolve(true);
    }),
    new Promise((resolve, reject) => {
      resolve(true);
    })
  ]
}

A promise is a value just like strings, numbers, arrays etc. You can treat it like any value. It just happens to be an object that has a .then() method and is awaitable

Note: actually, any object with a .then() method is awaitable even your own custom created non-promise object (actually any object with a .then() method is a promise even though it is not a Promise)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.