Reputation: 1381
I am writing a promise, where the first part of my promise is doing a git clone
in shelljs (node.js app). The second part of the promise is doing a git pull
and more. But many times the promise starts the clone and then before that is over, jumps into the function holding other shell.js executions like git pull
. But then it does not find the repo. What am I missing here?
My code:
let myPromise = new Promise((rev, err) => {
console.log('create promise');
rev();
});
myPromise.then(() => {
shell.cd(' ..');
shell.cd('git_folder');
fs.access('git_repo', function(error) {
if (error) {
console.log("Directory does not exist.")
shell.exec(`git clone the_git_repo && echo "cloned"`);
} else console.log("Directory exists.");
})
}).then(() => nextFunc());
const nextFunc = () => {
shell.cd('git_repo');
shell.exec('git pull');
//other git commands
}
Sometimes my promise runs in order, and other times, it starts the clone and goes into the nextFunc
function but does not find the git_repo
folder. Is there anyway to finish the clone and only then execute nextFunc
.
Upvotes: 1
Views: 128
Reputation: 350272
The problem is that the main then
callback doesn't return a promise, so the promise returned by that then()
is immediately resolved, when the fs.access
callback hasn't executed yet.
You should have a promise that resolves when access
has done its asynchronous task. For that you can use fs.promises
: it exposes the same methods (like access
) but returning a promise instead of taking a callback.
So that part of the code can be:
myPromise.then(() => {
shell.cd('..');
shell.cd('git_folder');
return fs.promises.access('git_repo');
}).then(() => {
console.log("Directory exists.");
}).catch(error => {
console.log("Directory does not exist.");
shell.exec(`git clone the_git_repo && echo "cloned"`);
}).then(nextFunc);
Upvotes: 0