我正在尝试使用async / await,但是没有从等待返回。
这是等待的异步函数。
async _checkEmailDuplication() {
try {
console.log('Check Email Duplication is called');
let res = await MyNetwork.checkEmail(this.state.email);
console.log('Check email return value: ' + res);
if (res === 0) {
console.log('Available Email');
return false;
}
else {
console.log('Email Duplication Check Error');
return true;
}
}
catch (e) {
console.error('Check Email Call Error', e.message);
return true;
}
console.log('What happened?');
return true;
}
它正在调用checkEmail函数,这是检查电子邮件功能定义
export type EmailCheckResponse = { ret?: number };
class Network {
constructor() {
this._network = NativeModules.NetworkService;
}
checkEmail = (email: string): Promise<EmailCheckResponse> => {
console.log('Network CheckEmail is called');
return this._network.checkEmail(email);
}
}
这是react-native模块,并尝试使用iOS中的Nativemodule。
这是Objective-C Native模块导出部分。
RCT_EXPORT_METHOD(checkEmail:(NSString *)email
resolver:(RCTPromiseResolveBlock)resolve
rejecter:(RCTPromiseRejectBlock)reject)
{
@autoreleasepool {
[GRPCCall useInsecureConnectionsForHost:kHostAddress];
AccountService *client = [[AccountService alloc] initWithHost:kHostAddress];
EmailCheckRequest *request = [EmailCheckRequest message];
request.email = email;
NSLog(@"Requested Email: %@\n", request.email);
[client checkEmailWithRequest:request handler:^(EmailCheckResponse *response, NSError *error) {
NSLog(@"Email Check result: %d\n", response.ret);
}];
}
}
问题是在调用checkEmail后,它被卡住了。没有回报。
日志说
2017-07-16 16:01:29.355 [info] [tid:com.facebook.React.JavaScript]检查电子邮件重复被称为 2017-07-16 16:01:29.356 [info] [tid:com.facebook.React.JavaScript]调用网络CheckEmail 2017-07-16 16:01:29.364 [50446:3725293]要求的电子邮件:xxx@xxx.com 2017-07-16 16:01:29.384 [50446:3725170]电子邮件查看结果:0
似乎Objective-C模块被成功调用,但没有从它回来。在调用await checkEmail之后,没有任何反应。
有没有人可以告诉我的代码有什么问题? =(
答案 0 :(得分:0)
我可以从您的React原生模块实现中看到,您忘记调用resolve
和reject
方法,这些方法对于按照承诺的方式工作承诺至关重要。
[client checkEmailWithRequest:request handler:^(EmailCheckResponse *response, NSError *error) {
NSLog(@"Email Check result: %d\n", response.ret);
if(response){
resolve(response);
}else{
reject(@"no_events", @"There were no events", error);
}
}
];
希望这会对你有所帮助。