我是 node.js
的完整初学者。我刚刚读到我们可以使用 .then()
函数以特定顺序执行多个函数。我打算这样写代码:
function one(){
console.log("one")
}
function two(){
console.log("two")
}
function three(){
console.log("three")
}
one().then(two()).then(three())
但我收到了这个错误:
TypeError: Cannot read property 'then' of undefined
at Object.<anonymous> (C:\chat\test.js:10:6)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.runMain (module.js:604:10)
at run (bootstrap_node.js:389:7)
at startup (bootstrap_node.js:149:9)
at bootstrap_node.js:502:3
原文由 anonymous 发布,翻译遵循 CC BY-SA 4.0 许可协议
.then
是存在于Promises上的一种方法,是一种代码同步机制。您的代码不是异步的,因此您不需要使用 Promise。你可以打电话如果您的代码执行异步操作,那么您可以使用承诺和
.then
。异步操作是诸如读取/写入文件、http 请求、计时器等等之类的东西。举个例子,我们可以使用内置的
Promise
来创建我们自己的异步操作:_我不建议您正常执行此操作。我们只是用它作为一个例子。在大多数情况下,您可以调用已经为您返回承诺的函数_。
另请注意,当您使用
.then
时,您需要传递一个 _回调_。two()
立即调用two
函数,所以它与() => two()
。接下来,您可以经常使用
async
/await
而不是.then
我认为在大多数情况下这会使您的代码更容易推理。这与重写为使用
await
而不是.then
的第二个示例相同。您可以将await
之后的所有内容视为在.then
链接到await
之后的表达式的内部。Finally, you should handle errors by either chaining
.catch
to the promises or using the normaltry
/catch
inside ofasync
functions.