承诺同步方法 [英] Promisify a synchronous method

查看:73
本文介绍了承诺同步方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以通过使用promise将同步方法转换为异步方法吗?

Can I make a synchronous method into asynchronous by using promise?

例如同步读取文件(是的,有 fs.readFile 具有回调):

For example reading a file synchronously (yes there is fs.readFile which has callback):

// Synchronous read
var data = fs.readFileSync('input.txt'); 

我应该这样做:

function readFileAsync(){
    return new Promise((resolve, reject) => {
        try {
          resolve(fs.readFileSync('input.txt')); 
        } catch(err) {
          reject(err);
        }
    })
}

或使用异步/等待:

 function async readFileAsync(){
            try {
              let result = await fs.readFileSync('input.txt'); 
              return result;
            } catch(err) {
              return err;
            }
        })
    }


推荐答案

我将短语改写为从否到不是真的。

I would re-phrase the the other to answers from "No" to "Not Really".

首先要澄清一点:在NodeJS中,所有内容是异步的,除了您的代码。具体来说,您的代码中的一部分将永远不会与另一部分代码并行运行-但是NodeJS运行时可以在执行代码的同时管理其他任务(即IO)。

First a point of clarification: In NodeJS, everything is asynchronous, except your code. Specifically, one bit of your code will never run in parallel with another bit of your code -- but the NodeJS runtime may manage other tasks (namely IO) at the same time your code is being executed.

fs.readFile 之类的功能的美丽之处在于IO与代码并行发生。例如:

The beauty of functions like fs.readFile is that the IO happens in parallel with your code. For example:

fs.readFile("some/file",
            function(err,data){console.log("done reading file (or failed)")});
do.some("work");

第二行代码将在NodeJS忙于将文件读入内存时执行。 fs.readFileSync 的问题在于,当您调用它时,NodeJS会停止评估您的代码(如果有的话!),直到完成IO(即已将文件读入)为止。内存)。因此,如果您要问您是否可以使用阻塞(可能是IO)功能,并使用promises使其成为非阻塞功能?,答案肯定是否。

The second line of code will be executed while NodeJS is busily reading the file into memory. The problem with fs.readFileSync is that when you call it, NodeJS stops evaluating your code (all if it!) until the IO is done (i.e. the file has been read into memory, in this case). So if you mean to ask "can you take a blocking (presumably IO) function and make it non-blocking using promises?", the answer is definitely "no".

您可以使用Promise控制调用阻止功能的顺序吗?当然。承诺只是宣告回叫顺序的一种奇特方法,但是一切都可以用一个承诺来实现,可以使用 setImmediate()(尽管透明度降低了很多,但付出了更多的努力)。

Can you use promises to control the order in which a blocking function is called? Of course. Promises are just a fancy way of declaring the order in which call backs are called -- but everything you can do with a promise, you can do with setImmediate() (albeit with a lot less clarity and a lot more effort).

这篇关于承诺同步方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆