user2386092
user2386092

Reputation: 186

Iterate over normal functions and promises

Object.prototype.modify = function(modifications,prop){
  modifications.forEach(modifier => {
     this[prop] = modifier(this[prop])
  })
}

function removeLastName(str){
  return str.split(' ')[0]
}

function upperCase(str){
  return str.toUpperCase()
}

function translate(str){
  return new Promise((resolve,reject) => {
      setTimeout( _ => resolve(str+"translated"),1000)
  })
}

function prepareUser(user){
  user.modify([removeLastName,upperCase],'name')
  // user.modify([removeLastName,upperCase,trans],'name') 
  return user
}

var user = {
  name: "simon madsen"
}

console.log(prepareUser(user));

Hello, how I can get my modify function to use normal functions and functions that return a promise. Without having all my modifications functions returning promises, and without my modify function to return a promise.

Upvotes: 2

Views: 552

Answers (2)

user2386092
user2386092

Reputation: 186

Object.prototype.modify = function(modifications,prop){

  var modificationsPromises = modifications.map(modifier => {
    return Promise.resolve(modifier(this[prop]))
    .then( modifiedProp => {
        this[prop] = modifiedProp
     })
  })
  return Promise.all(modificationsPromises).then( _ => Promise.resolve(this))

}

Here is my solutions, thanks for the response.

Upvotes: 0

Attila
Attila

Reputation: 91

You could try converting all your synchronous functions to promises and use Promise.all, see https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

return Promise.all(modifications.map(item => {
  if (item instanceof Promise){
    return item
  } else {
    return new Promise(function(resolve, reject) {
      try {
        resolve(item(prop))
      } catch (err) {
        reject(err)
      }
    })
  }
}))

// Then get the value after everything resolves
user.modify([removeLastName,upperCase,translate],'name')
  .then(function(results) {
    user.name = results.pop()
    console.log(user)
  })
  .catch(function(err) {
    console.log('Oops', err)
  })

Upvotes: 1

Related Questions