简体   繁体   中英

How to execute a promise in nodejs with express

so I'm new to Node and I've been trying to do some work with promises. My problem is that I can't seem to get my endpoint to execute it's code 'asynchronously'. The idea is that my endpoint executes the 'list' function, which should log out words to the the console and return 'true' to the response. All my promise does is wait five seconds and print out 'Promise'. I'm expecting the console to print 'Before' 'After' 'Promise' (in that order), but I'm getting 'Before' 'Promise' 'After', which would appear to me to be synchronous execution. Shouldn't the list function move onto the last line of the code ('After') and not wait for the promise to resolve/reject?

var log4js = require('log4js');
var logger = log4js.getLogger('controller');
var Promise = require('promise');

function pause(milliseconds) {
    var dt = new Date();
    while ((new Date()) - dt <= milliseconds) { /* Do nothing */ }
}

var listPromise = function(){
    return new Promise(function (resolve, reject){
        var flag = true;

        try{
            pause(5000);
            console.log('Promise');
        }catch(err){
            logger.error('Error');
        }

        if(flag){
            resolve(flag);
        }else{
            reject(Error("Could not execute"));
        }
    });
}

 exports.list = function(req, res) {

     console.log('Before');

     listPromise().then(function(fulfilled) {
         res.json(fulfilled);
     })
     .catch(function (error) {
         res.send(error.message);
     });

     console.log('After');
 };

Promises aren't "executed", and you cannot use them to execute blocking code in parallel. They're values representing the future results of some asynchronous operation, nothing more. Your pause function is not asynchronous, and that's bad - use setTimeout instead. The callbacks will actually be asynchronous then:

function pause(milliseconds) {
    return new Promise(function (resolve, reject) {
        setTimeout(resolve, milliseconds);
        console.log('Promise executor');
    });
}

exports.list = function(req, res) {
     console.log('Before');
     pause(5000).then(function(fulfilled) {
         console.log("Promise callback");
         res.json(fulfilled);
     })
     .catch(function (error) {
         res.send(error.message);
     });
     console.log('After');
};

This will log Before , Promise executor , After , and then after five seconds, Promise callback .

Your listPromise function is not really async function, it returns the promise only. Use setTimeout function to emulate async operation:

 let listPromise = () => { return new Promise(resolve => { setTimeout(_ => { console.log('Promise'); resolve(true); }, 1000); }); } let list = () => { console.log('Before'); listPromise() .then(fulfilled => console.log(fulfilled)) .catch(err => console.log(err)); console.log('After'); }; list(); 

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