Tom Hanks
Tom Hanks

Reputation: 614

Promise "Resolve" is convert object to string?

This promise is converting my object to a string

cobraCommand() {

  const data = this.getData(localStorage.getItem('BusinessAddress'))

  new Promise((resolve, reject) => {

    if(data){
      let newData = this.removeEmptyProps(data)
      console.log(newData, "before RESOLVE")
      resolve(newData)
    }
  }).then(function(result) {

    console.log(result + "in THEN");

  }).then(function(result) {
    return result;
  })
}

data is an object and removeEmptyProps removes the fields with empty property values.

console.log(newData, "before RESOLVE")

returns

{name: "BusinessAddress"} "before RESOLVE"

.

console.log(result + "in THEN");

returns

[object Object]in THEN

Upvotes: 0

Views: 601

Answers (2)

jonatjano
jonatjano

Reputation: 3738

It's because you do object + string js transform the object into a string to be able to concatenate them. to do that it call Object.toString() which default to return "[object Object]" if you didn't create one in your object

you need to use a , between the object and the string if you don't want this call to toString

let obj = {}
console.log(obj+"")
console.log(obj.toString())
console.log(obj, "a string")

let objWithToString = {
  toString() {
    return "I have my own to string"
  }
}
console.log("objWithToString.toString() returns :" + objWithToString)

Upvotes: 2

Kevin.a
Kevin.a

Reputation: 4306

The reason this is happening is because you're using string concatenation. You're adding a string to an object with the + operator. This results in a string.

Like mentioned in the comments above you can do :

console.log(result, "in THEN");

Upvotes: 0

Related Questions