Search code examples
node.jspromise

JavaScript, Promise, what's wrong with it?


I'm very new to Promises. I have the following code:

    const cintTotalRequests = 25000;
    var blnNext = true, intRequest = 0;
    do {
        if ( blnNext != true ) {
            continue;
        }
        blnNext = false;
        info.msg("Request#" + (++intRequest));
        info.msg("Creating promise");
        var myPromise = new Promise(function(myResolve, myError) {
            const cstrURI = "http://localhost:8000/"
                        + "?cn=Tesla&cy=2024&cm=1&cd=8&ds=clickcomp&rt=10&u=1";
            http.get(cstrURI, res => {
                let data = [];
                const headerDate = res.headers 
                                && res.headers.date 
                                ? res.headers.date : 'no response date';
                info.msg('Status Code:', res.statusCode);
                info.msg('Date in Response header:', headerDate);

                res.on("data", chunk => {
                    data.push(chunk);
                });
                res.on('end', () => {
                    info.msg('Response ended: ');
                    myResolve(data);                    
                });
            }).on("error", err => {
                var strMsg = "ERROR:" + err.message;
                info.msg(defs.RED + strMsg + defs.RESET);
                myError(strMsg);
            });
        });
        myPromise.then(function(data) {
            console.log("myPromise.resolve(" + data + ")");
        }, fnError = function(strError) {
            console.log("myPromise.reject(" + strError + ")");
        });
        break;
    } while( intRequest < cintTotalRequests );    

As far as I can see the callback on the http.get isn't called. I've put console.log in the callback to see if it's executed. It isn't. Can anyone help because I know the request isn't being received by the server as thats also running on my system with debug enabled.

With the break in the while loop, it works for one iteration. I need to learn how to implement await.


Solution

  • The core issue - this is not how Node.js work. It has something called Eventloop and the principle is very straightforward. It has just one thread that executes your code (there is actually thread pool for I/O operations, but thats invisible for you). The Eventloop takes event on "top" which at some point is the code you post and execute ALL synchronous context it has first. Then takes another event to process.

    So that do-while will always be first fully executed as it is synchronous part of your app (even if it runs for hour) before the callback http.get(cstrURI, res => { is executed.

    If you need to wait for promise to be finished first, you need to return it from this part of the app and somewhere write myPromise.then(...) and put whatever you want in that .then part


    To answer to your question we need more code/context of what you are doing.

    Maybe this will help you understand how it works:

    const promise = new Promise((resolve,reject) => {
      console.log('I will set new callback in next line. Then the synchronous part will continue and that will be executed later');
      setTimeout(()=> {
        console.log('Executing after timeout')
        resolve('Resolving promise');
      }, 1000);
      
      console.log('Promise is constructor - if you create it, the synchronous part is executed as well');
    });
    
    promise.then(str=>console.log(str));
    
    console.log('The program finishes the synchronous part here and something else can be executed once availablein Event Loop');

    The core question is - why do you even need Promises or how the rest of the app look like?

    In general, if you just write

    http.get(cstrURI, res => {}); it will do the GET request, no promises needed