简体   繁体   English

如何创建异步方法的同步版本?

[英]How to create a Sync version of an Async method?

I'm trying to achieve something similar to the methods you get with the core fs module where you have an Async method by default and a Sync method if requested such as fs.readDir() and fs.readDirSync() ; 我正在尝试实现与您通过核心fs模块获得的方法类似的方法,在该模块中,默认情况下您具有Async方法,并且在需要时具有Sync方法,例如fs.readDir()fs.readDirSync()

I have a method called fetchUrls that fetches files from a list of urls and returns a promise. 我有一个名为fetchUrls的方法,该方法从URL列表中获取文件并返回fetchUrls I want to add another method called fetchUrlsSync which calls fetchUrls and blocks the thread until the promise is resolved. 我想添加另一个名为fetchUrlsSync方法,该方法调用fetchUrls并阻塞线程,直到解决承诺为止。 how can that be done? 那怎么办?

sample code: 样例代码:

fetchUrls(startDate, endDate) {
    return new Promise((resolve, reject)=> {
        // some async work...
    })
}

fetchUrlsSync() {
 // call fetchUrls and block until resolved
}

those two functions are methods on a class. 这两个函数是类上的方法。

This isn't possible directly in node.js. 这不可能直接在node.js中实现。 It also goes against the general model in node, which is to perform all IO asynchronously. 它也违背了节点中的通用模型,后者是异步执行所有IO的。

It is however possible to use a compiled Node.js extension to achieve this called http-sync . 但是,可以使用已编译的Node.js扩展来实现此功能,称为http-sync

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

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