Open
Description
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
Labels
No labels