掌握JavaScript中的Promise,实现异步编程 (5)

如果你用纯Promise+then()的方式进行代码编写,它将是这样的:

"use strict"; const idAndName = new Map([ [1, "Jack"], [2, "Tom"], [3, "Mary"], ]); const personnelInformation = new Map([ [1, { gender: "female", age: 18, addr: "TianJin", desc: "my name is Mary" }], [2, { gender: "male", age: 21, addr: "ShangHai", desc: "my name is Tom" }], [3, { gender: "male", age: 18, addr: "BeiJing", desc: "my name is Jack" }], ]); const nameAndMessage = new Map([ [1, 3], [2, 2], [3, 1], ]) function getUserMessage(id) { let userName, messageId, message, str; new Promise((resolve, reject) => { // 获取姓名 if (idAndName.has(id)) { userName = idAndName.get(id); resolve(); } reject(`no information id : ${id}`); }) .then(() => { // 获取关系 messageId = nameAndMessage.get(id); }) .then(() => { // 获取信息 message = personnelInformation.get(messageId); }) .then(() => { // 进行渲染 str = `name : ${userName}</br>`; for (let [k, v] of Object.entries(message)) { str += `${k} : ${v}</br>`; } document.write(str) }) .catch(reason => { document.write(`<p>${reason}</p>`); }) } getUserMessage(3);

如果你使用async+awit的方式编写,那么它的逻辑就会清楚很多:

"use strict"; const idAndName = new Map([ [1, "Jack"], [2, "Tom"], [3, "Mary"], ]); const personnelInformation = new Map([ [1, { gender: "female", age: 18, addr: "TianJin", desc: "my name is Mary" }], [2, { gender: "male", age: 21, addr: "ShangHai", desc: "my name is Tom" }], [3, { gender: "male", age: 18, addr: "BeiJing", desc: "my name is Jack" }], ]); const nameAndMessage = new Map([ [1, 3], [2, 2], [3, 1], ]) // 获取姓名 async function getName(id) { if (idAndName.has(id)) { return idAndName.get(id); } throw new Error(`no information id : ${id}`); } // 获取关系 async function getRelation(id) { return nameAndMessage.get(id); } // 获取信息 async function getMessage(messageId) { return personnelInformation.get(messageId); } // 入口函数,进行渲染 async function getUserMessage(id) { try { let userName = await getName(id); // 必须等待该函数执行完成才会继续向下执行 let messageId = await getRelation(id); let message = await getMessage(messageId); let str = `name : ${userName}</br>`; for (let [k, v] of Object.entries(message)) { str += `${k} : ${v}</br>`; } document.write(str) } catch (e) { document.write(`<p>${e}</p>`); } } getUserMessage(3); 异常处理

async+await的异常处理推荐使用try+catch语句将所有执行代码进行包裹,它将处理所有可能出现的异常,相当于在链式调用的最后面加上catch()方法:

"use strict"; async function task01() { console.log("run task 01"); } async function task02() { throw new Error("task02 error"); console.log("run task 02"); } async function task03() { console.log("run task 03"); } async function main() { try { await task01(); await task02(); await task03(); } catch (e) { console.log(e); } } main();

也可以在主函数外部使用catch()方法来处理异常,但是我并不推荐这么做。

"use strict"; async function task01() { console.log("run task 01"); } async function task02() { throw new Error("task02 error"); console.log("run task 02"); } async function task03() { console.log("run task 03"); } async function main() { await task01(); await task02(); await task03(); } main().catch(reason => { console.log(reason); });

除此之外,你也可以使用try+catch语句块对单独的async函数语句块进行处理,预防可能出现的异常。

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zyxwjz.html