meiser
meiser

Reputation: 31

Await for function that returns promise when event occurs

I'm reading post data with a function, when it reads all data on "end" it returns a promise, the problem is that when it returns the promise the function doesn't resume. This is the code:

    if (true) {
        log.check(ip, async function (c) {
            if (c) {
                const data = await ReadPost(req).catch(function (err) {
                    console.error(err);
                });

                    console.log("Error:m" + data);

        }
    });
}

function ReadPost(req) {
    var data = "";
    if (req.method === 'POST') {


        req.on('data', function (buffer) {
                data += buffer;
            });

        req.on('end', function () {
            data = data.toString();
            console.log("Data:" + data);
            return Promise.resolve(data);
        });
    }
    else {
        return Promise.reject();
    }
}

}

I don't know if its possible to do it that way, to solve this I would put the rest of the function below the await inside req.on end, also is possible for req.on end to be called twise?

Upvotes: 0

Views: 333

Answers (1)

Luca Kiebel
Luca Kiebel

Reputation: 10096

The function doesn't actually return a Promise, it returns undefined, or rejects a Promise. To make it work with await, you have to return a Promise at the top of the function, and then call resolve in the onend listener:

function ReadPost(req) {
  return new Promise((resolve, reject) => {
    var data = "";
    if (req.method === 'POST') {


      req.on('data', function(buffer) {
        data += buffer;
      });

      req.on('end', function() {
        data = data.toString();
        console.log("Data:" + data);
        resolve(data);
      });
    } else {
      reject();
    }
  });

}

Here the function returns a Promise right away before listening to the end, or data listeners.

Upvotes: 2

Related Questions