-1

How to return values from promise in this case:

 async foo() {
   let [error, data] = await this.promiseFoo();
 ....
 }

 promiseFoo() {
   return Promise.resolve(this.asyncFoo()).then((error, data) => 
   [error, data]);
 }

Getting error and data undefined inside then(). How can I return error and data from asyncFoo? When callback it looks like: this.asyncFoo((error, data) => {...});

But I what to avoid using callback this time.

MolecularMan
  • 227
  • 2
  • 16
  • `asyncFoo` takes the callback as an **argument**. You might be interested in `promisify` found in libraries like Bluebird. Alternatively, create a wrapper for asyncFoo which creates a new Promise. – cbr Oct 27 '17 at 17:11
  • A promise never resolves with *both* an error and a result. Why would you want to return them as a pair? Why not use the normal `try { let data = await this.asyncFoo(); … } catch(error) { … }`? – Bergi Oct 28 '17 at 08:19
  • it's necessary for business logic to return both error and data – MolecularMan Oct 28 '17 at 09:58

2 Answers2

1

I think you're looking for

promiseFoo() {
    return this.asyncFoo().then(data => [null, data], error => [error, null]);
}
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • well your answer was right if he wanted to do try catch but he want to get the error as a resolve and not as catch – Amit Wagner Oct 28 '17 at 17:53
  • 2
    @AmitWagner The onrejected handler fulfills the returned promise as well? The code does pretty much the same as your answer but is safer, simpler, shorter and more efficient. – Bergi Oct 28 '17 at 20:36
  • i checked what you said and its works great. to bad i didn't know that before. could have saved some code writing good tip(: – Amit Wagner Oct 28 '17 at 22:01
  • @AmitWagner See the [difference between `.then(…, …)` and `.then(…).catch(…)`](https://stackoverflow.com/q/24662289/1048572) for details – Bergi Oct 28 '17 at 22:35
0

try change your promiseFoo to

promiseFoo() {
   return new Promise ((resolve,reject) =>{
     asyncFoo()
     .then( data =>{
        resolve([null, data])
     }  )
     .catch(err =>{
        resolve([err,null])
     })
   })
 }
Amit Wagner
  • 3,134
  • 3
  • 19
  • 35
  • Avoid the [`Promise` constructor antipattern](https://stackoverflow.com/q/23803743/1048572?What-is-the-promise-construction-antipattern-and-how-to-avoid-it)! – Bergi Oct 28 '17 at 08:18