中国优质的IT技术网站
专业IT技术创作平台
IT职业在线教育平台
封装调用系统hash方法时,由于异步处理,在hash处理前返回了结果。
微信扫码分享
/** 获取 hash 调用入口 */ public async getHash() { // then 方案 this.hashByPromise("11111111", "???") .then((data) => { AlertDialog.show({ message: "hash: " + baseUtil.base64Encode(data) }); console.log("hash: " + baseUtil.uint8ArrayToHexStr(data)); }); // await 方案 let data: Uint8Array = await this.hashByPromise("11111111", "???"); console.log("hash: " + baseUtil.uint8ArrayToHexStr(data)); } // callback 方案 public async hashByCallback(strPlain: string, strHashAlg: string): Promise<Uint8Array> { let reHash: Uint8Array = new Uint8Array(); if (strPlain.length != 0) { let plain: Uint8Array = baseUtil.stringToUint8Array(strPlain); Logger.verbose("index", "#######finalChallenge2"); reHash = await this.doHashByCallback(plain, "SHA256", (reHash: Uint8Array) => { Logger.verbose("index", "#######finalChallenge5"); return reHash; }); } return reHash; } //promise 用法与 callback 相差不大: // Promise 方案 public async hashByPromise(strPlain: string, strHashAlg: string): Promise<Uint8Array> { let reHash: Uint8Array = new Uint8Array(); if (strPlain.length != 0) { let plain: Uint8Array = baseUtil.stringToUint8Array(strPlain); Logger.verbose("index", "#######finalChallenge2"); reHash = await this.doHashByPromise(plain, "SHA256") .then((reHash: Uint8Array) => { Logger.verbose("index", "#######finalChallenge5"); return reHash; }); } return reHash; } public async doHashByPromise(strPlain: Uint8Array, hashAlg: string): Promise<Uint8Array> { Logger.verbose("index", "#######finalChallenge3"); let reHash: Uint8Array = new Uint8Array([]); try { let md: cryptoFramework.Md = cryptoFramework.createMd(hashAlg); let digestPlain: cryptoFramework.DataBlob = { data: strPlain }; // 数据量较少时,可以只做一次update,将数据全部传入,接口未对入参长度做限制 let promiseMdUpdate = md.update(digestPlain); reHash = await promiseMdUpdate.then(() => { let promiseMdDigest = md.digest(); return promiseMdDigest; }).then(mdOutput => { Logger.verbose("index", "#######finalChallenge4"); // 返回计算结果 return mdOutput.data; Logger.verbose("index", "[Promise]: MD result mdOutput: " + mdOutput.data); }).catch((error: BusinessError) => { Logger.error("index", "[Promise]: error: " + error.message); // 返回空结果 return new Uint8Array([]); }); } catch (error) { let e = error as BusinessError; Logger.verbose("index", "[Callback]: error code: " + e.code + ", message is: " + e.message); } return reHash; }