matmik
matmik

Reputation: 670

How to read Promise resolved value from a function call

I have 2 functions in total, one function that is returning a new Promise and resolving to a variable, like so:

  function promiseTest(data) {
    const delay = 200;
    return new Promise(resolve => setTimeout(() => resolve(data), delay));
  }

and then another function where I'm calling this function, and then inserting for the data variable a JSON object.

    function getInfo() {
     return promiseTest(require('./allData.json'));
    }

So my question is, how do I read the data that the Promise is resolving from the getInfo function, just in a simple console.log?

Say: console.log(getInfo().data) (but obviously this doesn't work but hopefully helps with what I'm after).

Upvotes: 3

Views: 1993

Answers (3)

Antoine Boisier-Michaud
Antoine Boisier-Michaud

Reputation: 1665

There are a few ways to do this.

Async/await

JavaScript introduced the async and await keywords a few years ago. It's a special syntax simplifying asynchronous programming. You can make your functions async, and use await when calling them. It basically wraps the whole . then() mess.

async function promiseTest(data) {
    const delay = 200;
    return new Promise(resolve => setTimeout(() => resolve(data), delay));
}


async function getInfo() {
    return await promiseTest(require('./allData.json'));
}

Then, you can then get getInfo()'s result by awaiting it:

console.log(await getInfo());

Here are some reading which should help you:

https://javascript.info/async-await https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Instructions/async_function

.then()

You can also go with the old way, using then:

function promiseTest(data) {
    const delay = 200;
    return new Promise(resolve => setTimeout(() => resolve(data), delay));
}


function getInfo() {
    return promiseTest(require('./allData.json'));
}

getInfo().then(data => console.log(data));

Pass a callback

You could pass a callback to your getInfo method.

function promiseTest(data) {
    const delay = 200;
    return new Promise(resolve => setTimeout(() => resolve(data), delay));
}


function getInfo(callback) {
    promiseTest(require('./allData.json')).then(data => callback(data));
}

getInfo(data => console.log(data));

Upvotes: 2

Vincent Schöttke
Vincent Schöttke

Reputation: 4716

The value that the promise returns is passed as the first parameter into the .then function.

Please see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then

In your case that could be: getInfo().then(data => console.log(data));

Hope this helps.

Upvotes: 1

xenocratus
xenocratus

Reputation: 126

With promises you have to use/extract the data using a .then(); so

getInfo().then((data) => console.log(data));

Is there a particular reason why you need to use a promise? Your example seems suited to simply using the setTimeout function

Upvotes: 2

Related Questions