简体   繁体   中英

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).

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

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.

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() . 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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM