Wednesday, 10 May 2017

Using promises with Node JS express

I am newbie to promises, I am trying to understand how do they work.

Here my questions at first:

  1. When request is handled in a route function, does it wait for all promises, I mean that when I am using promise or callback it is a new scope and execution continues further.

  2. If I keep a req/res objects for example in timer and then respond to user, what will user see ? A request will just be blocked until I explicitly send response ?

So I have encountered the following problems.

Here is my route.

router.post('book', authHandler.provideMiddleware(), (req, res) => {
      bookManager.createBook(req.body, {
            onSuccess: function (data) {
               respondSuccess(res,HttpStatus.OK, {'data': data});
            },
            onError: function (message) {
                respondError(res, HttpStatus.HTTP_STATUS.BAD_REQUEST, {'error': message});
            }
        });
});

Inside bookmanager I have the following

  createBook(data, hook) {
        let book = createBookFromRequest(data);
        let verifyData = new Promise((resolve, reject) => {
            let valid = checkBookData(book);
            if(valid) {
               resolve(book);
            }
            else {
                reject("Invalid data");
            }
        });
        let createBook = new Promise((resolve, reject) => {
            book.save((err, result) => {
                if (!err) {
                    reject("Error while saving");
                }
                else {
                    resolve(result);
                }
            });

        });
        verifyData
            .then(() => {
                return createBook;
            })
            .then((data) => {
                hook.onSuccess(data);
            })
            .catch((error) => {
                hook.onError(error);
            });
    }

My idea is to chain multiple functions and if any error occurred, call hook.onError method, otherwise call on success.

I have several problems here.

  1. When error is thrown, my book is still created.
  2. I have the following error

    node:8753) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 6): Error: Can't set headers after they are sent.

I want to use the approach like Rx (Reactive Extensions).

Could someone explain what is wrong and how do promises really work in this case ?



via e109848

No comments:

Post a Comment