简体   繁体   English

包装在promise与同步功能中的异步功能

[英]Async function wrapped in promise vs. sync function

So I've always wondered if there is any benefit to this. 所以我一直想知道这样做是否有好处。 I'll give examples below. 我将在下面给出示例。

Asynchronous function wrapped in a Promise: 包装在Promise中的异步函数:

(async () => {
    await new Promise((resolve, reject) => {
        fs.writeFile(filePath, dataToWrite, (error) => {
            if (error) {
                reject(error);
                return;
            }
            resolve();
        });
    });
})();

Synchronous function: 同步功能:

(() => {
    fs.writeFileSync(filePath, dataToWrite);
})();

The only thing I know from light reading is that the synchronous function call blocks the process until done. 从光读中我唯一了解的是,同步函数调用会阻塞该过程,直到完成为止。 So for example a web server with api endpoints will not be able to process those requests until the synchronous function is done. 因此,例如,具有api端点的Web服务器将无法处理这些请求,直到完成同步功能。 Is this also true for the asynchronous function wrapped in a promise? 对于包含在promise中的异步函数也是如此吗? If there are any differences between the two and could one give an explanation if so? 如果两者之间有任何区别,可以的话可以解释一下吗?

The synchronous function call blocks the process until done. 同步函数调用将阻止该过程,直到完成。

Yes. 是。

Is this also true for the asynchronous function wrapped in a promise? 对于包含在promise中的异步函数也是如此吗?

No, that's the point of asynchronous processing. 不,这就是异步处理的重点。

The await only "blocks" the execution of the code of the particular async function until the awaited promise settles, but everything else will continue running. await仅“阻止”特定async function代码的执行,直到等待的承诺成立为止,但其他所有操作将继续运行。

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

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