Passing arguments to promises. Should I break the chain?
I am new to nodejs and promises. I have a requirement to pass arguments to a callback function in my promise chain. It looks something like this:
var first = function(something) {
/* do something */
return something.toString();
}
var second = function(something, item) {
/* need to work with both the args */
}
And my promise chain looks like
function(item) {
/* the contents come from first callback and the item should be passed as an argument to the second callback */
fs.readFile(somefile).then(first).then(second)
}
I need to pass an element as a parameter, can I do this without breaking my chain?
Please correct me if I am completely wrong.
thank
+3
source to share
2 answers
Wrap your function second
in an anonymous function and pass it like this:
function(item) {
/* the contents come from first callback and the item should be passed as an argument to the second callback */
fs.readFile(somefile)
.then(first)
.then(firstResult => second(firstResult, item))
}
+5
source to share