A
A
Alexander Knyazev2017-01-23 16:57:02
JavaScript
Alexander Knyazev, 2017-01-23 16:57:02

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

In the called module, the function is exported:
module.exports = {
findMaxSavedID: function(){
    InfoObject.findOne().sort('-postID').exec(function(err, item){
        return item;
    })
}
}

How to make a promise understand that it needs to wait until the function included in it is executed, that is, until it returns a value?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vitaly, 2017-01-23
@alexandrknyazev13071995

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.

V
Vitaly, 2017-01-23
@vshvydky

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

Call via
openPage()
    .then(response=>{ */.... /*})
    .catch(error=>{ */.... /*});

update2:
I do not recommend making a function in which a promise will be created and executed, since this function will be executed asynchronously and if necessary, continue the code, you will not be able to catch its result, it will be executed no one knows when, in parallel with the continuing code.
Always return a promise and call it where necessary, then you can work through the then chain or use async await or vo(generator) by waiting for an asynchronous response in yield.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question