简体   繁体   中英

Once a Promise is completed why is console.log the only output example?

This is not a duplicate question, this is an attempt to get a very specific detail from the exhaustive explanation at How do I return the response from an asynchronous call? which is not covered.

I don't quite understand the abstruse answers to resolving Promises.

I'm attempting to understand how to unwrap my data from a returned Promise. console.log(data) doesn't answer the question. "How do I get my payload?".

Why is is this a bloody secret?

I used node REPL to track my coding. I'm doing everything right except the last step, and I'm punching in the dark here.

someasyncFunction()
.then(data => data);

is supposed to return the "unwrapped" payload right? So why am I getting

$ node gettest.js 
Promise { <pending> }

There is a technical piece I am missing and I can't seem to get any help answering that last piece.

const https = require('https');
const datastore = {};

async function getInfo (){
        https.get('https://www.gnu.org/software/bash/manual/html_node/Command-Line-Editing.html#Command-Line-Editing', (resp) => {
        let data='';

        resp.on('data', (chunk) => {
            data += chunk;
        });

        resp.on('end', () => {
            //console.log(data);
            return data;
                        });
        }).on("error", (err) => {
            console.log("Error: " + err.message);
        });
}

datastore.info = getInfo().then(function (val){
    return val;
});

console.log(datastore.info);

getInfo is a Promise, also the method then returns a Promise itself.

You are assigning your variable to a Promise, so obviously you'll get a reference of it.

As the question that you linked said, you should embrace the asynchronous nature of JavaScript, and your flow is just synchronous from the top to bottom. It's just asynchronous inside the getInfo function, but that's not enough since out of it the flow remains synchronous.

I advise you, just to understand what you are doing, to don't use async/await, since it lets you think that everything is synchronous while it's not.

So only use the val value inside the then function:

getInfo().then(function (val){
    // Your async code here
});

Once you are confident with this way of thinking, you can refactor it using async/await , which is almost syntactical sugar to have a better looking code:

(async function () {
  async function getInfo () {
    // your code
  }

  datastore.info = await getInfo();

  console.log(datastore.info);

})();

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