闲话少说,直接上代码:
- (void)dispatch_async_main:(JSValue *)function { NSParameterAssert(function); dispatch_async(dispatch_get_main_queue(), ^{ [function callWithArguments:nil]; }); }
异步主线程,只是将dispatch_async进行了简单的包装;
- (void)dispatch_async_global_queue:(JSValue *)function afterFunction:(JSValue *)afterFunction { NSParameterAssert(function); NSParameterAssert(afterFunction); dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ JSValue *result = [function callWithArguments:nil]; [afterFunction callWithArguments:@[result]]; }); }
异步全局队列,也是简单的包装,之前看过一片关于JS锁的文章,里面说不管是在哪个线程调用js代码,只要JSContext相同就都会在主线程调用,如果想实现真正的异步,需要新建js虚拟机,后续会进行测试验证;
- (void)dispatch_after:(NSInteger)time function:(JSValue *)function { NSParameterAssert(time); NSParameterAssert(function); dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(time * NSEC_PER_SEC)); dispatch_after(delayTime, dispatch_get_main_queue(), ^{ [function callWithArguments:nil]; }); }
同上,这里都不赘述了,关于其他GCD相关的需要的时候进行封装即可;