Im a newbie javascript developper and this is my first time as a stackoverflow user but I have got valuable information from reading posts here.
I need to load a file but the code should wait because of the asynchronous nature of it. I thought a Promise might work and it is almost working but it's just still not waiting (synchronous) for the file to load. It does however wait at the end when there is no file. It should be the other way around it should wait until the file is loaded. then continue and run the next function which needs the data.
Can anyone tell me why my promise is not working? Should I even be using a promise for this or a callback?
Here is the code:
// ...
var p = new Promise(function (resolve, reject) {
let x = getTheData(); // async data but program don’t wait.
if (!x) { //if no data I want to wait?
resolve('success');
console.log('success');
}else {
reject('failure');
console.log('failure');
}
});
p.then(function () {
let y = getNewFunctionThatNeedsTheAboveDataToWork();
res.send('y is not working ' + y);
}).catch(function(){
console.log('error');
});
return p;
I'm completely lost, any help would be graceful.