Answer the question
In order to leave comments, you need to log in
How to wait for the execution of an external function in a "promise"?
var DBHandler = require('./DBHandler.js')
function openPage(){
var promise = new Promise( function(resolve) {
var maxExistID = DBHandler.findMaxExistID();
resolve(maxExistID);
}
promise.then(
function() {
console.log(maxExistID)
}
)
}
module.exports = {
findMaxSavedID: function(){
InfoObject.findOne().sort('-postID').exec(function(err, item){
return item;
})
}
}
Answer the question
In order to leave comments, you need to log in
No way. Your value is returned not by a function, but by a callback in the request - carefully re-read your code. The findMaxSavedID function will always return undefined, or it needs to be promissed.
The external function must either be a promise or have a callback where you pass resolve
update:
How would I do it if I had to wait for an asynchronous function in the promise
function findMaxSavedID(cb, cbErr){
InfoObject.findOne().sort('-postID').exec(function(err, item){
if(err) cbErr(err);
else cb(item);
});
}
function openPage(){
return new Promise( function(resolve, reject) {
// добавляем таймаут, вдруг ваша функция навсегда уйдет в работу.
setTimeout(reject, 1000*60*3, 'timeout');
DBHandler.findMaxExistID(resolve, reject);
}
}
openPage()
.then(response=>{ */.... /*})
.catch(error=>{ */.... /*});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question