krave krave - 8 months ago 41
Javascript Question

How to pass arguments to function as then()'s argument in Promise chain with previous resolved value being kept?

I am running JavaScript in node v5.7.1. I am trying to find a smart way to pass arguments to the function as then()'s argument while the previous resolved value still being kept without interfering each other.

var p = new Promise(function (resolve) {

function logger (prefix) {
return function (resolvedValue) {
console.log(prefix + resolvedValue);

p.then(logger('Hello '));

This is what I can figure out so far. My aim is to let promise p to do something which will take some time, such as a database operation. After that, p returns the resolved value and I want to pass it as well as other arguments to the callback as
's argument.

But I need to write a function which return another function again and again to reach my goal. Is there any other smart ways to do this? Does spread/rest operator
help in this case?


Closures are totally fine to do this. You could also use a function expression:

function logger (prefix, resolvedValue) {
    console.log(prefix + resolvedValue);

p.then(x => logger('Hello ', x));

or even an array and destructuring:

function logger ([prefix, resolvedValue]) {
    console.log(prefix + resolvedValue);

Promise.all(['Hello', p]).then(logger);