之前在《JavaScript 基础知识:第 4 部分》中,我们讨论了 if 和 else 语句、for 和 while 循环。在这一部分,我们将看看:
评论很棒,我们现在要讨论它。这么晚了,你应该知道什么是评论了。不管怎样,我们程序中的一条注释并没有被执行。注释旨在记录我们的代码。在 Javascript 中添加注释的方法有3种。我们有内联、多行和 JsDoc。
在线
// this is a number const numberOfBirds = 3; // the above comment is useless since the initial value assigned to the variable // is physically a number and the variable name also has a number in it // so use comments wisely by using proper naming
多行
/* Everything in here is or will be ignored. Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. */ const emptyString = "";
JsDoc
/** * This is a multiline comment * * But used for documentation */
评论可以放在任何地方;但是,将它们放置在一行代码之后(或末尾)或者其下方或上方时请小心。
在 javascript 中,分号 ; 不是必需的,但有时它会有所帮助。有一些工具可以帮助您。分号表示语句的结束。很好。
缩进用于排列代码以使其清晰且易于阅读。 Tab 键(键盘上)用于缩进。缩进有时是“制表符”或“空格”。空间一般是2或4个,如果你使用的是vscode,则不用担心。
JavaScript Essentials:第 4 部分中有一些练习,包括但不限于“fizzbuzz”、密码和电子邮件验证等。如果您遵循我的伪代码,您会遇到一些问题。我将提供考虑顺序的片段。
单个数字的嘶嘶声
const givenNumber = 3; if (givenNumber % 3 === 0 && givenNumber % 5 === 0) { console.log("fizzbuzz"); } else if (givenNumber % 3 === 0) { console.log("fizz"); } else if (givenNumber % 5 === 0) { console.log("buzz"); }
数组的嘶嘶声
const numbers = [3, 6, 10, 15]; for (const givenNumber of numbers) { if (givenNumber % 3 === 0 && givenNumber % 5 === 0) { console.log("fizzbuzz"); } else if (givenNumber % 3 === 0) { console.log("fizz"); } else if (givenNumber % 5 === 0) { console.log("buzz"); } }
密码验证
const veryWeakPassword = "PrQ1V_"; // const veryWeakPassword = "rtfy67Fg"; // const veryWeakPassword = "OlJgRc__1qwPVa"; console.log(`Password validation for "${veryWeakPassword}"`); // - be six characters if (veryWeakPassword.length !== 6) { console.log( `- Password must have 6 characters => "${veryWeakPassword}" has '${veryWeakPassword.length}' characters` ); } // - start with uppercase p, 'P' else if (!veryWeakPassword.startsWith("P")) { console.log( `- Password must start with 'P' => it is ${veryWeakPassword.startsWith( "P" )} that "${veryWeakPassword}" starts with 'P'` ); } // - end with underscore else if (!veryWeakPassword.endsWith("_")) { console.log( `- Password must end with '_' => it is ${veryWeakPassword.endsWith( "_" )} that "${veryWeakPassword}" ends with '_'` ); } // - have uppercase q, 'Q' else if (!veryWeakPassword.includes("Q")) { console.log( `- Password must have uppercase q, 'Q' => it is ${veryWeakPassword.includes( "Q" )} that "${veryWeakPassword}" has 'Q'` ); } // - have lowercase r, 'r' else if (!veryWeakPassword.includes("r")) { console.log( `- Password must have lowercase r, 'r' => it is ${veryWeakPassword.includes( "r" )} that "${veryWeakPassword}" has 'r'` ); } // - have its fifth character as uppercase v, 'V' // fifth character with have index = fifth position - 1 = 4 // const fifthCharacter = veryWeakPassword[4] else if (veryWeakPassword.charAt(4) !== "V") { console.log( `- Password must have its fifth character as uppercase v, 'V' => "${veryWeakPassword}" has its 5th character as '${veryWeakPassword.charAt( 4 )}'` ); } else { console.log(`${veryWeakPassword} is a valid password`); }
其他一些解决方案将使用嵌套的 if 和 else。
// password validation const veryWeakPassword = "PrQ1V_"; // const veryWeakPassword = "rtfy67Fg"; // const veryWeakPassword = "OlJgRc__1qwPVa"; console.log(`Password validation for "${veryWeakPassword}"`); // - be six characters if (veryWeakPassword.length === 6) { if (veryWeakPassword.startsWith("P")) { if (veryWeakPassword.endsWith("_")) { if (veryWeakPassword.includes("Q")) { if (veryWeakPassword.includes("r")) { if (veryWeakPassword.charAt(4) === "V") { console.log(`${veryWeakPassword} is a valid password`); } else { console.log( `- Password must have its fifth character as uppercase v, 'V' => "${veryWeakPassword}" has its 5th character as '${veryWeakPassword.charAt( 4 )}'` ); } } else { console.log( `- Password must have lowercase r, 'r' => it is ${veryWeakPassword.includes( "r" )} that "${veryWeakPassword}" has 'r'` ); } } else { console.log( `- Password must have uppercase q, 'Q' => it is ${veryWeakPassword.includes( "Q" )} that "${veryWeakPassword}" has 'Q'` ); } } else { console.log( `- Password must end with '_' => it is ${veryWeakPassword.endsWith( "_" )} that "${veryWeakPassword}" ends with '_'` ); } } else { console.log( `- Password must start with 'P' => it is ${veryWeakPassword.startsWith( "P" )} that "${veryWeakPassword}" starts with 'P'` ); } } else { console.log( `- Password must have 6 characters => "${veryWeakPassword}" has '${veryWeakPassword.length}' characters` ); }
你对这两个片段有何看法?实际上,第二个片段虽然有效,但并不是那么好。
函数是一段可以重用的代码。通常,函数执行特定的操作。一件事。它可以是任何东西。
让我们看看 JavaScript 中函数的一般形式(结构)。
// this is a number const numberOfBirds = 3; // the above comment is useless since the initial value assigned to the variable // is physically a number and the variable name also has a number in it // so use comments wisely by using proper naming
我们可以有一个打印“hello world”的函数
/* Everything in here is or will be ignored. Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. */ const emptyString = "";
我们帮自己一个忙,用一个描述函数功能的名称来命名我们的函数。
现在,当我们有一个函数时,我们必须“调用”它才能执行它。要调用函数,您需要在函数名称后跟 ( 和 )。如果函数采用 参数 ,您将在 ( 和 ) 中传递 参数 。在我们的例子中,对于“hello world”函数,我们必须执行 printHelloWorld();.
/** * This is a multiline comment * * But used for documentation */
让我们朝着一个小方向前进,这将扩大我们的武器库并使创建函数变得有趣。考虑这个函数,它将两个数字相加,然后打印一条文本告诉您发生了什么。
const givenNumber = 3; if (givenNumber % 3 === 0 && givenNumber % 5 === 0) { console.log("fizzbuzz"); } else if (givenNumber % 3 === 0) { console.log("fizz"); } else if (givenNumber % 5 === 0) { console.log("buzz"); }
这能给你一些想法吗?我们可以使用函数编写“fizzbuzz”和验证。我们可以如此小气和精致,以至于我们将每个验证需求编写为一个函数。它发生了。只是不要做得太过分。
现在,考虑 add 函数。如果我们想添加不同的数字,我们该怎么办?我们可以创建另一个函数。我们也可以直接改变这些值。正确的?是的。您会对我们用函数实现的功能感到惊讶。
首先,如果我们想添加不同的数字,我们可以更改数字。
const numbers = [3, 6, 10, 15]; for (const givenNumber of numbers) { if (givenNumber % 3 === 0 && givenNumber % 5 === 0) { console.log("fizzbuzz"); } else if (givenNumber % 3 === 0) { console.log("fizz"); } else if (givenNumber % 5 === 0) { console.log("buzz"); } }
好吧,让我们将函数改为 6 和 100 相加。现在我们必须改变这个功能。对此有一个解决方案,那就是引入参数(通过变量获取数据)。然后我们将这些数据作为参数传递。
让我们分析一下我们的 add 函数。 add 函数对 x 和 y 以及操作数进行运算。我们可以通过将 x 和 y 作为参数传递给 x 和 y 不同的值。
const veryWeakPassword = "PrQ1V_"; // const veryWeakPassword = "rtfy67Fg"; // const veryWeakPassword = "OlJgRc__1qwPVa"; console.log(`Password validation for "${veryWeakPassword}"`); // - be six characters if (veryWeakPassword.length !== 6) { console.log( `- Password must have 6 characters => "${veryWeakPassword}" has '${veryWeakPassword.length}' characters` ); } // - start with uppercase p, 'P' else if (!veryWeakPassword.startsWith("P")) { console.log( `- Password must start with 'P' => it is ${veryWeakPassword.startsWith( "P" )} that "${veryWeakPassword}" starts with 'P'` ); } // - end with underscore else if (!veryWeakPassword.endsWith("_")) { console.log( `- Password must end with '_' => it is ${veryWeakPassword.endsWith( "_" )} that "${veryWeakPassword}" ends with '_'` ); } // - have uppercase q, 'Q' else if (!veryWeakPassword.includes("Q")) { console.log( `- Password must have uppercase q, 'Q' => it is ${veryWeakPassword.includes( "Q" )} that "${veryWeakPassword}" has 'Q'` ); } // - have lowercase r, 'r' else if (!veryWeakPassword.includes("r")) { console.log( `- Password must have lowercase r, 'r' => it is ${veryWeakPassword.includes( "r" )} that "${veryWeakPassword}" has 'r'` ); } // - have its fifth character as uppercase v, 'V' // fifth character with have index = fifth position - 1 = 4 // const fifthCharacter = veryWeakPassword[4] else if (veryWeakPassword.charAt(4) !== "V") { console.log( `- Password must have its fifth character as uppercase v, 'V' => "${veryWeakPassword}" has its 5th character as '${veryWeakPassword.charAt( 4 )}'` ); } else { console.log(`${veryWeakPassword} is a valid password`); }
我们没有将 x 和 y 的值作为 add 中的内部值,而是传递它们。现在参数和实参之间的区别在于参数是在创建(定义)函数时传递的。参数是调用函数时传递的值。所以在函数add(x, y)中,x和y是参数(我们可以说占位符,代表要传递给函数的数据)。在 add(3, 30); 中,3 和 30 作为参数传递(要处理的实际值)。请注意,参数和参数的顺序必须匹配,否则我们将陷入严重的债务。
你觉得足以挑战大佬们了吗?嗯,我想你可以。你只需要保持冷静并知道自己在做什么。我将提供一些片段。
// this is a number const numberOfBirds = 3; // the above comment is useless since the initial value assigned to the variable // is physically a number and the variable name also has a number in it // so use comments wisely by using proper naming
对“嘶嘶声”做同样的事情。在代码片段周围包裹一个函数。您不必对所使用的变量进行注释。看看需要将哪些数据传递给函数(输入)。
我们可以向函数传递任意多个参数。但是,我鼓励您设置一些限制。有一些专业人士说三个就足够了。有人说少于五个。你必须对此保持聪明才智。现在,假设只要参数数量超过三个,我们就会使用数组或对象。是的。我们可以传递一个数组或一个对象作为参数。
/* Everything in here is or will be ignored. Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. */ const emptyString = "";
通过完成这个函数来编写一个计算数字数组平均值的函数。
/** * This is a multiline comment * * But used for documentation */
此时,应该清楚函数可以接受参数。实际上,我们的函数在计算完成后将返回一个值或某个值。计算值从函数返回。返回值的函数的形式如下:
const givenNumber = 3; if (givenNumber % 3 === 0 && givenNumber % 5 === 0) { console.log("fizzbuzz"); } else if (givenNumber % 3 === 0) { console.log("fizz"); } else if (givenNumber % 5 === 0) { console.log("buzz"); }
还记得添加功能吗?我们不会将值记录在函数内,而是返回它并将该值分配给变量,然后稍后重用该值。
const numbers = [3, 6, 10, 15]; for (const givenNumber of numbers) { if (givenNumber % 3 === 0 && givenNumber % 5 === 0) { console.log("fizzbuzz"); } else if (givenNumber % 3 === 0) { console.log("fizz"); } else if (givenNumber % 5 === 0) { console.log("buzz"); } }
这就像我们所说的一样简单。对calculateInterest函数做同样的事情。
函数可以返回任何可返回的内容。
箭头函数是编写函数的另一种方式。通常,当我有一个简单的函数来执行非常小的“事情”或在数组或字符串方法中进行循环时,我会使用箭头函数。您可以使用它来代替函数声明(命名函数)。我们说“函数”,表示我们要创建一个函数。箭头函数与声明式函数具有相同的功能。
箭头函数之所以被称为箭头函数,是因为 =>(胖箭头运算符)。它的形式可能是您以前见过的:
const veryWeakPassword = "PrQ1V_"; // const veryWeakPassword = "rtfy67Fg"; // const veryWeakPassword = "OlJgRc__1qwPVa"; console.log(`Password validation for "${veryWeakPassword}"`); // - be six characters if (veryWeakPassword.length !== 6) { console.log( `- Password must have 6 characters => "${veryWeakPassword}" has '${veryWeakPassword.length}' characters` ); } // - start with uppercase p, 'P' else if (!veryWeakPassword.startsWith("P")) { console.log( `- Password must start with 'P' => it is ${veryWeakPassword.startsWith( "P" )} that "${veryWeakPassword}" starts with 'P'` ); } // - end with underscore else if (!veryWeakPassword.endsWith("_")) { console.log( `- Password must end with '_' => it is ${veryWeakPassword.endsWith( "_" )} that "${veryWeakPassword}" ends with '_'` ); } // - have uppercase q, 'Q' else if (!veryWeakPassword.includes("Q")) { console.log( `- Password must have uppercase q, 'Q' => it is ${veryWeakPassword.includes( "Q" )} that "${veryWeakPassword}" has 'Q'` ); } // - have lowercase r, 'r' else if (!veryWeakPassword.includes("r")) { console.log( `- Password must have lowercase r, 'r' => it is ${veryWeakPassword.includes( "r" )} that "${veryWeakPassword}" has 'r'` ); } // - have its fifth character as uppercase v, 'V' // fifth character with have index = fifth position - 1 = 4 // const fifthCharacter = veryWeakPassword[4] else if (veryWeakPassword.charAt(4) !== "V") { console.log( `- Password must have its fifth character as uppercase v, 'V' => "${veryWeakPassword}" has its 5th character as '${veryWeakPassword.charAt( 4 )}'` ); } else { console.log(`${veryWeakPassword} is a valid password`); }
或
// password validation const veryWeakPassword = "PrQ1V_"; // const veryWeakPassword = "rtfy67Fg"; // const veryWeakPassword = "OlJgRc__1qwPVa"; console.log(`Password validation for "${veryWeakPassword}"`); // - be six characters if (veryWeakPassword.length === 6) { if (veryWeakPassword.startsWith("P")) { if (veryWeakPassword.endsWith("_")) { if (veryWeakPassword.includes("Q")) { if (veryWeakPassword.includes("r")) { if (veryWeakPassword.charAt(4) === "V") { console.log(`${veryWeakPassword} is a valid password`); } else { console.log( `- Password must have its fifth character as uppercase v, 'V' => "${veryWeakPassword}" has its 5th character as '${veryWeakPassword.charAt( 4 )}'` ); } } else { console.log( `- Password must have lowercase r, 'r' => it is ${veryWeakPassword.includes( "r" )} that "${veryWeakPassword}" has 'r'` ); } } else { console.log( `- Password must have uppercase q, 'Q' => it is ${veryWeakPassword.includes( "Q" )} that "${veryWeakPassword}" has 'Q'` ); } } else { console.log( `- Password must end with '_' => it is ${veryWeakPassword.endsWith( "_" )} that "${veryWeakPassword}" ends with '_'` ); } } else { console.log( `- Password must start with 'P' => it is ${veryWeakPassword.startsWith( "P" )} that "${veryWeakPassword}" starts with 'P'` ); } } else { console.log( `- Password must have 6 characters => "${veryWeakPassword}" has '${veryWeakPassword.length}' characters` ); }
让我们用箭头函数重写add函数。
function functionName(/* parameters */) { // do something }
=>,表示从 x y 表达式返回值。所以隐式使用了 return 关键字。同样,我们可以使用 return 关键字从函数显式返回一个值,但是,我们必须添加函数块。
// this is a number const numberOfBirds = 3; // the above comment is useless since the initial value assigned to the variable // is physically a number and the variable name also has a number in it // so use comments wisely by using proper naming
两者之间的区别在于,在第二个中,我们添加了一个块 { 和 } 以及一个从函数返回值的 return 关键字。同样,您可以选择是否返回值。
我们可以将函数作为参数传递给其他函数。本质上,我们将函数视为值。让我们考虑这个简单的例子。
/* Everything in here is or will be ignored. Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. */ const emptyString = "";
我们可以做到这一点的另一个地方是使用数组方法或字符串方法。考虑这个函数
/** * This is a multiline comment * * But used for documentation */
我们可以看到可以拉出回调函数,(total, element) =>总元素,0。其实就是我们可以替换的总元素。
const givenNumber = 3; if (givenNumber % 3 === 0 && givenNumber % 5 === 0) { console.log("fizzbuzz"); } else if (givenNumber % 3 === 0) { console.log("fizz"); } else if (givenNumber % 5 === 0) { console.log("buzz"); }
你知道我们传递了另一个函数,它接受 2 个数字参数并返回一个数字。我们甚至不需要创建一个函数。
我们之前已经做过一些数学运算,但这次我们将使用函数来抽象运算符。
const numbers = [3, 6, 10, 15]; for (const givenNumber of numbers) { if (givenNumber % 3 === 0 && givenNumber % 5 === 0) { console.log("fizzbuzz"); } else if (givenNumber % 3 === 0) { console.log("fizz"); } else if (givenNumber % 5 === 0) { console.log("buzz"); } }
最后一个参数称为默认参数,通常放置为
最后一个论点。这是你必须要做的事情
使用默认值。这个片段与之前的没有什么不同
一个除了引入默认参数,这意味着第三个
参数,我们可以选择是否为其传递值。
const veryWeakPassword = "PrQ1V_"; // const veryWeakPassword = "rtfy67Fg"; // const veryWeakPassword = "OlJgRc__1qwPVa"; console.log(`Password validation for "${veryWeakPassword}"`); // - be six characters if (veryWeakPassword.length !== 6) { console.log( `- Password must have 6 characters => "${veryWeakPassword}" has '${veryWeakPassword.length}' characters` ); } // - start with uppercase p, 'P' else if (!veryWeakPassword.startsWith("P")) { console.log( `- Password must start with 'P' => it is ${veryWeakPassword.startsWith( "P" )} that "${veryWeakPassword}" starts with 'P'` ); } // - end with underscore else if (!veryWeakPassword.endsWith("_")) { console.log( `- Password must end with '_' => it is ${veryWeakPassword.endsWith( "_" )} that "${veryWeakPassword}" ends with '_'` ); } // - have uppercase q, 'Q' else if (!veryWeakPassword.includes("Q")) { console.log( `- Password must have uppercase q, 'Q' => it is ${veryWeakPassword.includes( "Q" )} that "${veryWeakPassword}" has 'Q'` ); } // - have lowercase r, 'r' else if (!veryWeakPassword.includes("r")) { console.log( `- Password must have lowercase r, 'r' => it is ${veryWeakPassword.includes( "r" )} that "${veryWeakPassword}" has 'r'` ); } // - have its fifth character as uppercase v, 'V' // fifth character with have index = fifth position - 1 = 4 // const fifthCharacter = veryWeakPassword[4] else if (veryWeakPassword.charAt(4) !== "V") { console.log( `- Password must have its fifth character as uppercase v, 'V' => "${veryWeakPassword}" has its 5th character as '${veryWeakPassword.charAt( 4 )}'` ); } else { console.log(`${veryWeakPassword} is a valid password`); }
在 const Total = PerformActionOnArray(numArray, add); 中我们可以直接传递一个函数
// password validation const veryWeakPassword = "PrQ1V_"; // const veryWeakPassword = "rtfy67Fg"; // const veryWeakPassword = "OlJgRc__1qwPVa"; console.log(`Password validation for "${veryWeakPassword}"`); // - be six characters if (veryWeakPassword.length === 6) { if (veryWeakPassword.startsWith("P")) { if (veryWeakPassword.endsWith("_")) { if (veryWeakPassword.includes("Q")) { if (veryWeakPassword.includes("r")) { if (veryWeakPassword.charAt(4) === "V") { console.log(`${veryWeakPassword} is a valid password`); } else { console.log( `- Password must have its fifth character as uppercase v, 'V' => "${veryWeakPassword}" has its 5th character as '${veryWeakPassword.charAt( 4 )}'` ); } } else { console.log( `- Password must have lowercase r, 'r' => it is ${veryWeakPassword.includes( "r" )} that "${veryWeakPassword}" has 'r'` ); } } else { console.log( `- Password must have uppercase q, 'Q' => it is ${veryWeakPassword.includes( "Q" )} that "${veryWeakPassword}" has 'Q'` ); } } else { console.log( `- Password must end with '_' => it is ${veryWeakPassword.endsWith( "_" )} that "${veryWeakPassword}" ends with '_'` ); } } else { console.log( `- Password must start with 'P' => it is ${veryWeakPassword.startsWith( "P" )} that "${veryWeakPassword}" starts with 'P'` ); } } else { console.log( `- Password must have 6 characters => "${veryWeakPassword}" has '${veryWeakPassword.length}' characters` ); }
在任何事情之前,让我们定义一些术语。在我们的利基市场中,承诺很重要。
同步操作:这些操作是从上到下、一个接一个地顺序执行的。对于某些操作A1和A2,A1必须在A2执行之前完成。这样,A2 直到 A1 才会被执行。一次执行一个操作。这个缺点称为阻塞。
function functionName(/* parameters */) { // do something }
上面的输出按照上面写的线性顺序。
// function to print "hello world" function printHelloWorld() { console.log("Hello world"); }
简而言之,到目前为止我们编写的代码都是按同步顺序执行的,我们可以知道何时执行一行。
异步操作:这些是不按顺序执行的操作。这些操作同时运行。实际上,这些操作可能是同时运行的,一点一点地。由于一个操作的成功或执行与顺序无关,并且不会妨碍其他行的执行,因此我们将这种行为称为非阻塞。我们无法判断异步行何时被执行。
printHelloWorld(); // the output of this function will be on the console/terminal
这就是输出。
function add() { const x = 3; const y = 20; const sum = x + y; console.log(`${x} + ${y} = ${sum}`); } add(); // 3 + 20 = 23
你能根据输出识别异步操作吗?
就是setTimeout函数。假设它在后台运行。它是非阻塞的,所以最后的console.log被执行了。
一些异步操作
Promise 提供了一种管理或处理异步操作的方法。它是一种了解异步操作所处状态、执行时间以及是否“完成”或失败的方法。
让我们创造一个承诺
承诺的形式为:
// this is a number const numberOfBirds = 3; // the above comment is useless since the initial value assigned to the variable // is physically a number and the variable name also has a number in it // so use comments wisely by using proper naming
new 和 Promise 是关键字。 solve 和reject 是回调函数。我们可以用其他名称替换它们。通过转换,我们使用resolve和reject。
兑现承诺
Promise 有 then 方法,它提供解析值,catch 方法,它提供被拒绝的错误,还有finally,它是整个过程后清理的方法。最后是可选的。这是一个您可以玩玩的简单示例。
/* Everything in here is or will be ignored. Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. */ const emptyString = "";
查看输出并了解代码是如何执行的。 console.log("再见");并不是最后一个被处决的。我们使用 Promise 创建异步操作,并使用 then 和 catch 处理它。如果我们考虑按顺序执行这些操作,那么我们可以或必须将剩余的逻辑放入 then 块中。
/** * This is a multiline comment * * But used for documentation */
发生了什么?
这种处理 Promise 的方法的问题在于,我们倾向于嵌套或链接此操作,然后块会变胖,而且不那么友好。那么让我们看看 async 和 wait。
在正常的数据流中,我们不希望异步操作在后台运行。我们想听它并使用它的结果来做其他事情(就像我们在 then 和 catch 中所做的那样)。
让我们创建一个异步操作并使用 async 和 wait 来处理它。
我们知道如何创建命名函数和箭头函数。
const givenNumber = 3; if (givenNumber % 3 === 0 && givenNumber % 5 === 0) { console.log("fizzbuzz"); } else if (givenNumber % 3 === 0) { console.log("fizz"); } else if (givenNumber % 5 === 0) { console.log("buzz"); }
要使函数异步,我们使用 async 关键字。
const numbers = [3, 6, 10, 15]; for (const givenNumber of numbers) { if (givenNumber % 3 === 0 && givenNumber % 5 === 0) { console.log("fizzbuzz"); } else if (givenNumber % 3 === 0) { console.log("fizz"); } else if (givenNumber % 5 === 0) { console.log("buzz"); } }
现在无论什么操作进入函数块,假设在我们想要创建的异步函数中,我们都必须处理另一个异步操作,然后我们可以使用await。
const veryWeakPassword = "PrQ1V_"; // const veryWeakPassword = "rtfy67Fg"; // const veryWeakPassword = "OlJgRc__1qwPVa"; console.log(`Password validation for "${veryWeakPassword}"`); // - be six characters if (veryWeakPassword.length !== 6) { console.log( `- Password must have 6 characters => "${veryWeakPassword}" has '${veryWeakPassword.length}' characters` ); } // - start with uppercase p, 'P' else if (!veryWeakPassword.startsWith("P")) { console.log( `- Password must start with 'P' => it is ${veryWeakPassword.startsWith( "P" )} that "${veryWeakPassword}" starts with 'P'` ); } // - end with underscore else if (!veryWeakPassword.endsWith("_")) { console.log( `- Password must end with '_' => it is ${veryWeakPassword.endsWith( "_" )} that "${veryWeakPassword}" ends with '_'` ); } // - have uppercase q, 'Q' else if (!veryWeakPassword.includes("Q")) { console.log( `- Password must have uppercase q, 'Q' => it is ${veryWeakPassword.includes( "Q" )} that "${veryWeakPassword}" has 'Q'` ); } // - have lowercase r, 'r' else if (!veryWeakPassword.includes("r")) { console.log( `- Password must have lowercase r, 'r' => it is ${veryWeakPassword.includes( "r" )} that "${veryWeakPassword}" has 'r'` ); } // - have its fifth character as uppercase v, 'V' // fifth character with have index = fifth position - 1 = 4 // const fifthCharacter = veryWeakPassword[4] else if (veryWeakPassword.charAt(4) !== "V") { console.log( `- Password must have its fifth character as uppercase v, 'V' => "${veryWeakPassword}" has its 5th character as '${veryWeakPassword.charAt( 4 )}'` ); } else { console.log(`${veryWeakPassword} is a valid password`); }
await 告诉 javascript“等待”并从 Promise 接收已解决或已完成的值。
// password validation const veryWeakPassword = "PrQ1V_"; // const veryWeakPassword = "rtfy67Fg"; // const veryWeakPassword = "OlJgRc__1qwPVa"; console.log(`Password validation for "${veryWeakPassword}"`); // - be six characters if (veryWeakPassword.length === 6) { if (veryWeakPassword.startsWith("P")) { if (veryWeakPassword.endsWith("_")) { if (veryWeakPassword.includes("Q")) { if (veryWeakPassword.includes("r")) { if (veryWeakPassword.charAt(4) === "V") { console.log(`${veryWeakPassword} is a valid password`); } else { console.log( `- Password must have its fifth character as uppercase v, 'V' => "${veryWeakPassword}" has its 5th character as '${veryWeakPassword.charAt( 4 )}'` ); } } else { console.log( `- Password must have lowercase r, 'r' => it is ${veryWeakPassword.includes( "r" )} that "${veryWeakPassword}" has 'r'` ); } } else { console.log( `- Password must have uppercase q, 'Q' => it is ${veryWeakPassword.includes( "Q" )} that "${veryWeakPassword}" has 'Q'` ); } } else { console.log( `- Password must end with '_' => it is ${veryWeakPassword.endsWith( "_" )} that "${veryWeakPassword}" ends with '_'` ); } } else { console.log( `- Password must start with 'P' => it is ${veryWeakPassword.startsWith( "P" )} that "${veryWeakPassword}" starts with 'P'` ); } } else { console.log( `- Password must have 6 characters => "${veryWeakPassword}" has '${veryWeakPassword.length}' characters` ); }
当我们执行上面的代码片段时,我们会收到类似于以下内容的错误:警告:要加载 ES 模块,请在 package.json 中设置 "type": "module" 或使用 .mjs 扩展名..
我们可以轻松解决这个问题。运行命令 npm init -y。进入 package.json 文件并添加行“type”:“module”。 package.json 应该类似于
// this is a number const numberOfBirds = 3; // the above comment is useless since the initial value assigned to the variable // is physically a number and the variable name also has a number in it // so use comments wisely by using proper naming
现在,重新运行该代码片段,您应该会得到类似于
的输出
/* Everything in here is or will be ignored. Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. */ const emptyString = "";
现在,假设我们要处理 Promise 拒绝错误,如果没有,我们必须在异步调用周围使用 try 和 catch 子句。
/** * This is a multiline comment * * But used for documentation */
不会有任何 Promise 被拒绝,因为我们设置了 const result = true。将其设置为 false。我们的输出应该类似于
const givenNumber = 3; if (givenNumber % 3 === 0 && givenNumber % 5 === 0) { console.log("fizzbuzz"); } else if (givenNumber % 3 === 0) { console.log("fizz"); } else if (givenNumber % 5 === 0) { console.log("buzz"); }
因此,谈论 Promise 以及 async 和 wait 的目的是让您知道我们会经常这样做。参考上面列出的异步操作示例。
async 和await、try 和catch 以及finally 是关键字。
至此,我们已经讨论了函数和 Promise 以及如何处理它们,我认为我们大约 50% 具备了操纵数据(流)的“知识”。剩下的就是习惯编写 javascript 代码并成为一名称职的 javascript 程序员。亲自动手使用 JavaScript。这是您编写后端 API 的唯一方法,并且不会因为您有想法但不知道该怎么做而感到受到限制。
接下来是编写一些代码并解决一些问题,然后实际开始构建 API。这就是我们接下来要做的,不过,我鼓励您查看下面的资源。
这些材料有助于理解 Promise、异步和等待以及事件循环。
这些是一些您想尝试的练习。
以上是JavaScript 基础知识:第 5 部分的详细内容。更多信息请关注PHP中文网其他相关文章!