0

I'm trying to access a piece of data through an API and my company gives me a function called findItemById(id) that returns a JavaScript promise object. I'm also given a function called loadPromise("item", findItemById()) that takes a key value in the state object (we're using React.js) and a function and assigns that value to that key in state. I'm trying to use findItemById(id) to get the data I need, but I don't want to keep it in state. When I do this:

findItemById(id).then(function(result) {
    console.log(result);
}, function(err) {
    console.log(err);
});

I get the exact object I'm looking for in the console. But when I do:

const ObjectIWant = findItemById(id).then(function(result) {
    return result;
}, function(err) {
    return err;
});

console.log(ObjectIWant);

I get a JavaScript promise object back. If I drill down into the promise in the chrome develper tools, I can see the data I want in there. How can I return the data I'm looking for instead of a promise object?

matwlev
  • 315
  • 1
  • 2
  • 6
  • Can you please point me to the duplicate question? I've searched for an answer can haven't found anything that helps. – matwlev Nov 20 '17 at 14:14
  • This is expected behavior for JS; the data in a promise is loaded asynchronously, so it is only accessible in the promise callback. So the callback itself is, indeed, where you have access to the data. – DZack Nov 20 '17 at 22:36
  • Also, I think this is the duplicate: https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call?noredirect=1&lq=1 – DZack Nov 20 '17 at 22:39

0 Answers0