微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在 Node JS 中,我有一个无法解析的异步操作如何使用工作线程中止它?

如何解决在 Node JS 中,我有一个无法解析的异步操作如何使用工作线程中止它?

假设我有一个像这样的异步操作:

    async () => {
       await longTask().then(result => console.log(result));
    }

假设 longTask 是不可预测的。它挂起并且有时无法解决

我知道我们不能只是中止异步操作。

我研究了 worker threads 以便我可以生成一个工作程序来运行此异步操作并在需要时终止它。

不幸的是,当我尝试时,整个程序都退出了。

有没有办法让我中止/终止/取消/杀死一个工作线程并只删除异步操作,而不退出节点应用程序?

感谢您的时间。

解决方法

从关于集群 here 的 Node.js 文档中借用,一种可能的方法如下:

Main.js

    override func viewDidLoad() {
    
        super.viewDidLoad()
    
        let scrollingView = UIScrollView(frame: CGRect(x: CGFloat(20),y: CGFloat(20),width: CGFloat(view.bounds.size.width - 40),height: CGFloat(view.bounds.size.height - 40)))
    
        // we will set the contentSize after determining how many pages get filled with text
        //scrollingView.contentSize = CGSize(width: CGFloat((view.bounds.size.width - 20) * pageNumber),height: CGFloat(view.bounds.size.height - 20))
    
        scrollingView.isPagingEnabled = true
        view.addSubview(scrollingView)
    
        let textString = "NOW,what I want is,Facts.  Teach these boys and girls nothing but Facts.  Facts alone are wanted in life.  Plant nothing else,and root out everything else.  You can only form the minds of reasoning animals upon Facts: nothing else will ever be of any service to them.  This is the principle on which I bring up my own children,and this is the principle on which I bring up these children.  Stick to Facts,sir!’ The scene was a plain,bare,monotonous vault of a school-room,and the speaker’s square forefinger emphasized his observations by underscoring every sentence with a line on the schoolmaster’s sleeve.  The emphasis was helped by the speaker’s square wall of a forehead,which had his eyebrows for its base,while his eyes found commodious cellarage in two dark caves,overshadowed by the wall.  The emphasis was helped by the speaker’s mouth,which was wide,thin,and hard set.  The emphasis was helped by the speaker’s voice,which was inflexible,dry,and dictatorial.  The emphasis was helped by the speaker’s hair,which bristled on the skirts of his bald head,a plantation of firs to keep the wind from its shining surface,all covered with knobs,like the crust of a plum pie,as if the head had scarcely warehouse-room for the hard facts stored inside.  The speaker’s obstinate carriage,square coat,square legs,square shoulders,—nay,his very neckcloth,trained to take him by the throat with an unaccommodating grasp,like a stubborn fact,as it was,—all helped the emphasis. ‘In this life,we want nothing but Facts,sir; nothing but Facts!’ The speaker,and the schoolmaster,and the third grown person present,all backed a little,and swept with their eyes the inclined plane of little vessels then and there arranged in order,ready to have imperial gallons of facts poured into them until they were full to the brim."
    
        let textStorage = NSTextStorage(string: textString)
        let textLayout = NSLayoutManager()
        textStorage.addLayoutManager(textLayout)
        textLayout.delegate = self
    
        var r = CGRect(x: 0,y: 0,width: scrollingView.frame.size.width,height: scrollingView.frame.size.height)
    
        var i: Int = 0
    
        // this is what we'll use to track the "progress" of filling the "screens of textviews"
        // each time through,we'll get the last Glyph rendered...
        // if it's equal to the total number of Glyphs,we know we're done
        var lastRenderedGlyph = 0
    
        while lastRenderedGlyph < textLayout.numberOfGlyphs {
    
            let textContainer = NSTextContainer(size: scrollingView.frame.size)
            textLayout.addTextContainer(textContainer)
    
            let textView = UITextView(frame: r,textContainer: textContainer)
    
            r.origin.x += r.width
    
            textView.font = .systemFont(ofSize: 25)
    
            textView.tag = i
    
            i += 1
    
            scrollingView.addSubview(textView)
    
            // get the last Glyph rendered into the current textContainer
            lastRenderedGlyph = NSMaxRange(textLayout.glyphRange(for: textContainer))
    
        }
    
        // use the last textView rect to set contentSize
        scrollingView.contentSize = CGSize(width: r.origin.x,height: r.size.height)
    
        print("Actual number of pages =",i)
    }

Worker.js

2021-03-08 09:28:05,471 TRACE [org.wildfly.security.http.form] (default task-4) Authorizing username: [pet],Request URI: [http://localhost:8080/login/j_security_check],Context path: [/]
2021-03-08 09:28:05,471 TRACE [org.wildfly.security] (default task-4) Executing principalQuery...
2021-03-08 09:28:05,849 TRACE [org.wildfly.security] (default task-4) Role mapping:...
2021-03-08 09:28:05,849 TRACE [org.wildfly.security] (default task-4) Authorizing principal pet.
2021-03-08 09:28:05,849 TRACE [org.wildfly.security] (default task-4) Authorizing against the following attributes...
2021-03-08 09:28:05,849 TRACE [org.wildfly.security] (default task-4) Permission mapping: identity [pet] with roles [PAAKAYTTAJA] implies ("org.wildfly.security.auth.permission.LoginPermission" "") = true
2021-03-08 09:28:05,849 TRACE [org.wildfly.security] (default task-4) Authorization succeed
2021-03-08 09:28:05,849 TRACE [org.wildfly.security] (default task-4) Handling CachedIdentityAuthorizeCallback: principal = pet  authorizedIdentity = SecurityIdentity{principal=pet,securityDomain=org.wildfly.security.auth.server.SecurityDomain@57bbd492,authorizationIdentity=EMPTY,realmInfo=RealmInfo{name='myRealm',securityRealm=org.wildfly.security.auth.realm.AggregateSecurityRealm@2461c292},creationTime=2021-03-08T07:28:05.849Z}
2021-03-08 09:28:05,849 DEBUG [org.wildfly.security.http.form] (default task-4) User [pet] authenticated successfully
2021-03-08 09:28:05,849 TRACE [org.wildfly.security] (default task-4) Handling AuthenticationCompleteCallback: succeed
2021-03-08 09:28:05,849 TRACE [org.wildfly.security] (default task-4) Handling SecurityIdentityCallback: identity = SecurityIdentity{principal=pet,849 TRACE [org.wildfly.security.http.form] (default task-4) User redirected to default path [http://localhost:8080/login/]
2021-03-08 09:28:05,849 TRACE [org.wildfly.security] (default task-4) Role mapping: principal [pet] -> decoded roles [PAAKAYTTAJA] -> realm mapped roles [PAAKAYTTAJA] -> domain mapped roles [PAAKAYTTAJA]

这是我过去使用过几次的方法,并且对我非常有效。希望这能让您对如何为您的用例实现这一点有所了解。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。