iOS promise

三方框架

自定义demo:

#import <Foundation/Foundation.h>
#import "BlockTask.h"

NS_ASSUME_NONNULL_BEGIN

typedef _Nullable id (^TBlock)(id result);

@interface TaskQueue : NSObject

@property(nonatomic,strong) NSBlockOperation * preTask;
@property(nonatomic,strong) id result;

-(TaskQueue * )awaitBlockTask:(TBlock ) block;

@end

NS_ASSUME_NONNULL_END
#import "TaskQueue.h"

@interface TaskQueue ()
@property(nonatomic,strong) NSOperationQueue * taskQueue;
@end

@implementation TaskQueue

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self initQueue];
    }
    return self;
}

-(void)initQueue{
    _taskQueue = [[NSOperationQueue alloc] init] ;
}
-(TaskQueue * )awaitBlockTask:(TBlock) block{
    __block typeof(self) weakSelf = self;
    NSBlockOperation * task = [NSBlockOperation blockOperationWithBlock:^{
        weakSelf.result =  block(weakSelf);
    }];
    if (self.preTask) {
        [task addDependency:self.preTask];
    }
    [_taskQueue addOperation:task];
    self.preTask = task;
    return self;
}

@end

测试代码,不阻塞当前线程按顺序执行:

    NSLog(@"main start");
    
    TaskQueue * queue = [[TaskQueue alloc] init];
    
    [[[[queue awaitBlockTask:^id(TaskQueue*  preTask) {
        NSLog(@"task 1 ,%@",[NSThread currentThread]);
        return @"111";
        
    }] awaitBlockTask:^id(TaskQueue*  preTask) {
        [NSThread sleepForTimeInterval:3];
        NSLog(@"task 2 ,result:%@,%@",preTask.result ,[NSThread currentThread]);
        return @"222";
        
    }] awaitBlockTask:^id(TaskQueue*  preTask) {
        [NSThread sleepForTimeInterval:1];
        NSLog(@"task 3 ,result:%@,%@",preTask.result ,[NSThread currentThread]);
        return @"333";
        
    }] awaitBlockTask:^id(TaskQueue*  preTask) {
        NSLog(@"task 4 ,result:%@,%@",preTask.result ,[NSThread currentThread]);
        return @"444";
        
    }];
    NSLog(@"main end");

iOS promise

上一篇:hbuilderX打包苹果证书的申请方法


下一篇:安卓开发 利用百度识图api进行物体识别(java版)