码迷,mamicode.com
首页 > 移动开发 > 详细

iOS promise

时间:2021-04-20 15:43:40      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:ref   ace   -objc   nullable   github   测试   end   blank   strong   

三方框架

自定义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

标签:ref   ace   -objc   nullable   github   测试   end   blank   strong   

原文地址:https://www.cnblogs.com/qiyer/p/14675236.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!