Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract data out of a Promise

I have a promise that returns data and I want to save that in variables. Is this impossible in JavaScript because of the async nature and do I need to use onResolve as a callback?

Can I somehow use this (e.g. wrap it with async/await):

const { foo, bar } = Promise.then(result => result.data, errorHandler); // rest of script 

instead of this?

Promise.then(result => {    const { foo, bar } = result.data;    // rest of script  }, errorHandler); 

Note: Bluebird library is used instead of native implementation, and I can't change from Promise to asnyc/await or Generators.

like image 870
Tobias Mühl Avatar asked Apr 28 '16 09:04

Tobias Mühl


People also ask

How do you get the data out of a promise?

NO you can't get the data synchronously out of a promise like you suggest in your example. The data must be used within a callback function. Alternatively in functional programming style the promise data could be map()ed over.

How do you return a value from promise?

If a handler function: returns a value, the promise returned by then gets resolved with the returned value as its value. doesn't return anything, the promise returned by then gets resolved with an undefined value. throws an error, the promise returned by then gets rejected with the thrown error as its value.

How do you get data from promise object react?

To get promise value in React and JavaScript, we can use await . to create the getAnswer function that calls fetch with await to get the response data from the promise returned by fetch . Likewise, we do the same with the json method. And then we call setAns to set the value of ans .

How do I return a value from promise TypeScript?

To access the value of a promise in TypeScript, call the then() method on the promise, e.g. p. then(value => console. log(value)) . The then() method takes a function, which is passed the resolved value as a parameter.


1 Answers

NO you can't get the data synchronously out of a promise like you suggest in your example. The data must be used within a callback function. Alternatively in functional programming style the promise data could be map()ed over.

If your are OK using async/await (you should it's awesome) then you can write code that looks synchronous yet retain the asynchronicity of a promise (see @loganfsmyth comments).

const { foo, bar }  = await iAmAPromise.then(result => result.data); 

Overall since you are already using ES6 I assume you are also using a transpiler. In which case you should definitely give async/await a try. Just be sure to weight in the decision that as today they are not yet a ratified specification.

like image 105
silkAdmin Avatar answered Sep 27 '22 23:09

silkAdmin