简体   繁体   中英

Why this Javascript promise does not work?

I am Learning about promises.

app.get('/message',function(req, res){    
    var promise = new Promise(function(resolve, reject){
        resolve("hi");
    });
    promise.then(function(message){
       res.json(message);
    })

});

This works good. Though This is too simple. To write something 'lengthy' I moved the code out of app.get() and tried to return the message from the external function... like this:

    app.get('/message',function(req, res){ 
      var message = message(); // I also tried wrapping this in promise and calling `res.json` in `promise.then()` but no luck
       res.json(message);
    });

    function message(){    
        var promise = new Promise(function(resolve, reject){
            resolve("hi");
        });
        promise.then(function(message){
           return message;
        })

    }

So why doesn't the return statement in the message() function return the message ? and what's the best practice to move such promising code out of my route functions?

First, you have a local variable named message which masks the module level variable which has the same name and references a function. You need to rename one of them.

Then: You don't have a return statement for the message function, so it returns undefined .

If you want to get the result of the promise back in the callback function you pass to get then you need to:

  1. Return the promise
  2. Call then on it
  3. Use res.json(...); inside the function you pass to then

For example:

app.get('/message',function(req, res){ 
  var my_message = message(); 
  my_message.then(function (data) {
     res.json(data);
 });
});

function message(){    
    var promise = new Promise(function(resolve, reject){
        resolve("hi");
    });
    return promise;
}

Your message function doesn't return anything.

You could do:

app.get('/message',function(req, res){
    message().then(function (message) {
        res.json(message);
    }
});

function message() {    
    return new Promise(function(resolve, reject){
        resolve("hi");
    });
}

Also, be careful to not use the same names for multiple variables, since it makes the code error-prone due to less readabililty.

You can return promise from your message function and use async/await on it like:

app.get('/message', async function(req, res){
    var msg = await message();
    res.json(msg);
});
function message() {    
    return new Promise(function(resolve, reject){
        resolve("hi");
    });
}

Like:

 function message() { return new Promise(function(resolve, reject) { setTimeout(resolve, 1500, 'hi'); }); } async function go() { console.log('Async call started...'); var msg = await message(); console.log(msg); } go(); 

The function message does not return the created promise. Normally you'd have an error saying: cannot read property .then of undefined

function message(){    
    var promise = new Promise(function(resolve, reject){
        resolve("hi");
    });
    return promise.then(function(message){  // This will return the initial promise. Due to to the .then, that promise is chained into resolving into the message
       return message;
    })

}

It could be shorted though (in case you do not want the .then in your message function. Just return the promise then:

function message(){    
return new Promise(function(resolve, reject){
    resolve("hi");
});

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM