runJobs method

int runJobs(
  1. Pointer<Void> rtHandle,
  2. Pointer<Void> ctxHandle
)

Implementation

int runJobs(Pointer<Void> rtHandle, Pointer<Void> ctxHandle) {
  // Prevent recursion: if this runtime is already running jobs, skip
  if (_busyRuntimes.contains(rtHandle.address)) {
    return 0;
  }
  _busyRuntimes.add(rtHandle.address);
  try {
    int totalExecuted = 0;
    bool hasMore;
    do {
      hasMore = false;

      // 1. 处理挂起的异步 Promise (Resolvers)
      final ctxAddr = ctxHandle.address;
      if (ctxAddr != 0) {
        final resolvers = JSObject.pendingResolvers[ctxAddr];
        if (resolvers != null && resolvers.isNotEmpty) {
          final ids = resolvers.keys.toList();
          for (final id in ids) {
            final val = resolvers.remove(id);
            final out = ffi.calloc<QjsResult>();
            QuickJsFFI.writeOut(out, val);
            _asyncResolve(ctxHandle, id, out);
            freeQjsResult(out);
            hasMore = true;
          }
        }

        // 2. 处理挂起的异步 Promise (Rejections)
        final rejections = JSObject.pendingRejections[ctxAddr];
        if (rejections != null && rejections.isNotEmpty) {
          final ids = rejections.keys.toList();
          for (final id in ids) {
            final reason = rejections.remove(id) ?? 'Unknown error';
            final cstr = reason.toNativeUtf8();
            _asyncReject(ctxHandle, id, cstr);
            ffi.malloc.free(cstr);
            hasMore = true;
          }
        }
      }

      // 3. 执行 QuickJS 自身的任务队列
      if (_runJobs(rtHandle) > 0) {
        hasMore = true;
      }

      if (hasMore) totalExecuted++;
    } while (hasMore);

    return totalExecuted;
  } finally {
    _busyRuntimes.remove(rtHandle.address);
  }
}