0

I would use an async function as normal synchronous function, I tried use await but it still doesn't work.

const getScript = (url) => {
return new Promise((resolve, reject) => {
    const http = require('http'),
        https = require('https');

    let client = http;

    if (url.toString().indexOf("https") === 0) {
        client = https;
    }

    client.get(url, (resp) => {
        let data = '';

        // A chunk of data has been recieved.
        resp.on('data', (chunk) => {
            data += chunk;
        });

        // The whole response has been received. Print out the result.
        resp.on('end', () => {
            resolve(data);
        });

    }).on("error", (err) => {
        reject(err);
    });
});
};

async function getBody(url) {

(async (url) => {
    return ("qwe" + await getScript(url));
})(url);
}


console.log(getBody('http://myurl.com/myapi'));


console.log("end");

But it still doesn't load the data before the console.log "end". Where did I go wrong?

Nimantha
  • 6,405
  • 6
  • 28
  • 69
  • Possible duplicate of https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – Estus Flask Jan 14 '19 at 21:53

4 Answers4

0

Asynchronous function cannot be converted to synchronous. a in asynchronous means that it's not synchronous. async can converted to regular function, but it will still be asynchronous.

Asynchronicity is contagious. Once it's async (promise-based), it's preferable to stick to promise control flow.

There should be top-level async function at some point, and async IIFE inside getBody is redundant. It should be:

async function getBody(url) {
    return ("qwe" + await getScript(url));
}

(async () => {
    console.log(await getBody('http://myurl.com/myapi'));
    console.log("end");
})()
Estus Flask
  • 206,104
  • 70
  • 425
  • 565
-1

It will be await not async

async function getBody(url) {

(await (url) => {
    return ("qwe" + await getScript(url));
})(url);
ellipsis
  • 12,049
  • 2
  • 17
  • 33
-1

It is because you are not awaiting for the result.Here when the IIFE is been executed (which is async) it returned a promise. You are not awaiting for the IIFE to be resolved. Thus you should simply add await in front of IIFE like -

async function getBody(url) {
    await (async (url) => { // add await before executing this function right away
        return ("qwe" + await getScript(url));
    })(url);
Komal Bansal
  • 789
  • 2
  • 7
  • 20
-2

Try this:

async function getBody(url) {
    let r = await getScript(url));
    return ("qwe" + r);
}

(async () => {
    let b = await getBody('http://myurl.com/myapi')
    console.log(b);
    console.log("end");
}) ();
Zoe
  • 27,060
  • 21
  • 118
  • 148
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345