Chen
Chen

Reputation: 970

Put Javascript Promise into Functions

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

Upvotes: 0

Views: 60

Answers (3)

slebetman
slebetman

Reputation: 113866

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)

Upvotes: 1

Bergi
Bergi

Reputation: 664395

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);
})

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 370689

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);
});

Upvotes: 1

Related Questions