Search code examples
javascriptes6-promise

How change the order of 'this' when passing it through bind in JavaScript?


I have the following code do illustrate my problem.

var p = Promise.resolve('this-is-the-title');
createFilePath=(title, ex)=>{
  let ready = `${title.split(' ').join('-')}.${ex}`
  console.log(ready)
  return Promise.resolve(ready)
}
makeFile=(path,content)=>{
  return{
    file: path,
    content
  }
}
p
  .then(createFilePath.bind(this,'md'))

What will be logged is md.this-is-the-title. Is there a way to change the order of this (something like .then(createFilePath.bind('md', this)))

createFilePath is used by other functions so I would not like to go through the code and change createFilePath(ex,title).


Solution

  • Currently your use of bind is equivalent to this:

    p.then(function(promiseValue) {
        return createFilePath.call(this, 'md', promiseValue)
    })
    

    Here the promiseValue is the value of the promise p, which is 'this-is-the-title' in your example. bind is being used to 'partially apply' the arguments of the function createFilePath but you can only do that from left-to-right, you can't skip over the first argument and just specify the second argument. You can do it yourself using a wrapper function:

    p.then(function(promiseValue) {
        return createFilePath.call(this, promiseValue, 'md')
    })
    

    If you don't need the this value inside createFilePath (which you don't in your example but you might in your real code) then you can simplify this further:

    p.then(function(promiseValue) {
        return createFilePath(promiseValue, 'md')
    })