I want to assign a promise to a variable in the following way:
const createSingleUser = function createSingleUser(userData) {
return new Promise((resolve, reject) => {
new User(userData)
.save()
.then((user) => {
resolve(user, 'user');
})
.catch((error) => {
reject(error);
});
});
};
let createUsers;
if (users instanceof Array) {
// If we have an array, we're batch creating users
createUsers = new User().createBatchUsers(users); // returns promise
} else {
// If we have a single object, we're only creating one user
createUsers = new User().createSingleUser(users); // returns promise
}
createSingleUser(users)
createUser
.then((result) => {
.....
However this does not work due to timing issues. Is there another way to make such a construct without having to write the promise chain twice?
Edit As @torazaburo mentions, If you create a promise, it will start running. You can assign it to a variable, but the variable will represent the running promise. This is the problem I'm facing. This is the case since createSingleUser is a (Promise) object and not a function.