简体   繁体   English

如何使异步函数成为普通的同步函数

[英]How to make async function to an ordinary synchronous function

i would use an async function as normal synchronous function, i tried use await but it still doesn't work. 我会使用异步功能作为正常的同步功能,我尝试使用等待,但仍然无法正常工作。 Where did i wrong? 我在哪里错了?

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". 但是它仍然不会在console.log“ end”之前加载数据。 Where did i wrong? 我在哪里错了? Thank you 谢谢

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. async可以转换为常规函数,但仍将是异步的。

Asynchronicity is contagious. 异步性具有传染性。 Once it's async (promise-based), it's preferable to stick to promise control flow. 一旦async (基于承诺),最好坚持承诺控制流。

There should be top-level async function at some point, and async IIFE inside getBody is redundant. 某些时候应该有顶级的async功能,而getBody中的async getBody是多余的。 It should be: 它应该是:

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

(async () => {
    console.log(await getBody('http://myurl.com/myapi'));
    console.log("end");
})()

It will be await not async 它将等待不异步

async function getBody(url) {

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

It is because you are not awaiting for the result.Here when the IIFE is been executed (which is async) it returned a promise. 这是因为您不等待结果。在执行IIFE(异步)时,它会返回一个Promise。 You are not awaiting for the IIFE to be resolved. 您不是在等待IIFE解决。 Thus you should simply add await in front of IIFE like - 因此,您只需在IIFE前面添加await,例如-

async function getBody(url) {
    await (async (url) => { // add await before executing this function right away
        return ("qwe" + await getScript(url));
    })(url);

Try this (I write code from head) 试试看(我从头开始写代码)

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");
}) ();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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