resolving a javascript promise

472 views Asked by At

Below outlines a promise that has two simple steps display on the console something, then display something else after the first step is completed.

I am trying to understand how to resolve the promise, and allow the 2nd step to complete.

var lookup_documents = new Promise(
    function(resolve, reject) {
        console.log("1st");
        //resolve(); - How do I do this outside of this function?
    }

);

lookup_documents.then(
    function() {
        console.log("2nd");
    }
);
2

There are 2 answers

0
olivarra1 On

Normally you use new Promise() when you want to wrap some asynchronous function into a promise, such as:

new Promise((resolve, reject) => {
    makeAjaxCall((err, data) => {
        if(err) return reject(err);
        else return resolve(data);
    })
});

There are other Promise implementations, such as q, where you can create a "deferred" object that returns a promise... Something similar would be:

function makeAjaxCallPromise() {
    let deferred = Q.defer();
    makeAjaxCall((err, data) => {
        if(err) return deferred.reject(err);
        else return deferred.resolve(data);
    });
    return deferred.promise;
}

For the specific thing you want... All I can think of is declare a variable outside of the promise function scope and asign it, something like:

let resolver, rejecter;
new Promise((resolve, reject) => {
    resolver = resolve;
    rejecter = reject;
});
makeAjaxCall((err, data) => {
    if(err) return resolver(err);
    else return rejecter(data);
});

But that doesn't look too good and can lead to errors... Try to wrap everything in your Promise function.

4
Martin van Driel On

You can do it like this, using your example - if I understand you correctly.

var lookup_documents = function() {
  return new Promise(function(resolve, reject) {
    console.log("1st");
    resolve();
  });
};

lookup_documents().then(function() {
  console.log("2nd");
});