Search code examples
javascriptnode.jscallbackes6-promise

Why resolve parameter comes first in JavaScript Promises?


I was learning javascript Promises. To me, it looked like JavaScript Promise works similar to a callback function.

In a callback function, we usually use the first parameter as an error, and the second as a success.

Then why in JavaScript Promise, parameters come differently? First is the success and second is the error? It's like the opposite of the callback parameter structure and it confuses me.

This isn't a problem, but I would like to have an explanation for this. If I am wrong, then what am I missing?


Solution

  • You are confusing JavaScript promises callbacks with callback design patterns from the Node standard library's API. They are not the same.

    The purpose of JavaScript promises is to deal with long running processes where we need some ability to figure out when the process is finished to continue running the next snippet of code.

    So in the Promises callbacks that you are learning about there are 3 states: unresolved, resolved, and rejected.

    By default, a Promise exists in an unresolved state, that means you just made the Promise and you are waiting for something to happen, some long running process such as an Ajax request or some other event to occur, once it occurs, that Promises enters into either one of the two other states, resolved or rejected.

    The above is not the purpose and function of Node standard library's callbacks which are used inside of functions that are part of the filesystem API. These particular functions such as read(), readdir() and so on have three arguments that can be passed to it, one being optional, the third being the callback which you speak of.

    The pattern for Node standard library callbacks when working with filesystem functions is to offer two arguments in that callback argument, the first one always being an error object, err, now it's not guaranteed that an error is going to occur, instead if something goes wrong when opening up some file(s), Node is going to call the callback with the first argument of the err object.

    If there is no error, then the first argument is going to instead be null.

    Now the second argument to the callback function is going to be the data I am actually looking for.

    https://nodejs.org/api/fs.html#fs_file_system

    You see, two different callbacks you are talking about.