Skip to content

Inconsistent behavior with using DispatchQueue on Node vs Electron #4

Open
@KishanBagaria

Description

@KishanBagaria
import NodeAPI
import Foundation

final class AwesomeClass: NodeClass {
  static let properties: NodeClassPropertyList = [
    "foo": NodeMethod(foo),
  ]
  private static let queue = DispatchQueue(label: "new-queue")
  private let swiftJSQueue: NodeAsyncQueue
  
  init(_ args: NodeFunction.Arguments) throws {
    self.swiftJSQueue = try NodeAsyncQueue(label: "new-async")
  }

  private static func returnAsync(
      on jsQueue: NodeAsyncQueue,
      _ action: @escaping () throws -> NodeValueConvertible
  ) throws -> NodePromise {
      try NodePromise { deferred in
          queue.async {
              let result = Result { try action() }
              try? jsQueue.async {
                  try deferred(result)
              }
          }
      }
  }
  private func returnAsync(
      _ action: @escaping () throws -> NodeValueConvertible
  ) throws -> NodePromise {
      try Self.returnAsync(on: swiftJSQueue, action)
  }
  private func performAsync(
      _ action: @escaping () throws -> Void
  ) throws -> NodePromise {
      try returnAsync {
          try action()
          return NodeUndefined.deferred
      }
  }

  func foo(bar: String, baz: String) throws -> NodeValueConvertible {
    try performAsync { 
      print("\(bar) \(baz)")
      DispatchQueue.main.sync {
        print("inside queue: \(bar) \(baz)")
      }
      print("outside queue: \(bar) \(baz)")
    }
  }
}

@main struct AwesomeMod: NodeModule {
  let exports: NodeValueConvertible

  init() throws {
    exports = try NodeObject([
      "AwesomeClass": AwesomeClass.constructor(),
    ])
  }
}
const swift = require(`./binaries/${process.platform}-${process.arch}/node.node`)

new swift.AwesomeClass().foo("a", "b").then(() => console.log("foo promise resolved"))
console.log('done')
$ node index.js
a b
done
^C

$ electron index.js
a b
done
inside queue: a b
outside queue: a b
foo promise resolved
^Cnode_modules/electron/dist/Electron.app/Contents/MacOS/Electron exited with signal SIGINT

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions