如何在 node.js 中使用 .then()? [英] How to use .then() in node.js?
问题描述
我是 node.js
的完全初学者.我刚刚读到我们可以使用 .then()
函数以特定顺序执行多个函数.我打算这样写代码:
I'm a complete beginner in node.js
. I've just read we can use .then()
function for executing several functions in particular order. I was going to write the code this way:
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
推荐答案
.then
是 Promise 上存在的一个方法,是一种代码同步机制.您的代码不是异步的,因此您不需要使用承诺.你可以打电话
.then
is a method that exists on Promises and is a mechanism for code synchronization. Your code is not asynchronous, so you wouldn't need to use promises. You can just call
one();
two();
three();
如果您的代码执行异步操作,那么您可以使用 promise 和 .then
.异步操作包括读/写文件、http 请求、计时器等.
If your code does something asynchronous, then you can use promises and .then
. Asynchronous operations are things like reading/writing files, http requests, timers, and many more.
举个例子,我们可以使用内置的Promise
来创建我们自己的异步操作:
Just as an example, we can use the built in Promise
to create our own asynchronous operations:
我不建议您正常执行此操作.我们只是以它为例.在大多数情况下,您可以调用已经为您返回承诺的函数.
function one() {
return new Promise(resolve => {
console.log("one");
resolve();
});
}
function two() {
return new Promise(resolve => {
console.log("two");
resolve();
});
}
function three(){
console.log("three")
}
one().then(() => two()).then(() => three());
还要注意,当你使用.then
时,你需要传递一个回调.two()
立即调用 two
函数,所以它和 () => 不一样.二()
.
Also note that when you use .then
, you need to pass a callback. two()
calls the two
function immediately, so it's not the same as () => two()
.
接下来,您通常可以使用 async
/await
而不是 .then
我认为这使您的代码在大多数情况下更容易推理.
Next, you can often use async
/await
instead of .then
which I think makes your code easier to reason about in most cases.
async function run() {
await one();
await two();
three();
}
run();
这与重写为使用 await
而不是 .then
的第二个示例相同.您可以将 await
之后的所有内容视为链接到 await
之后的表达式的 .then
内部.
This is the same as the second example rewritten to use await
instead of .then
. You can think of everything after await
as being inside of a .then
chained to the expression after await
.
最后,您应该通过将 .catch
链接到 Promise 或在 中使用普通的
函数.try
/catch
来处理错误异步
Finally, you should handle errors by either chaining .catch
to the promises or using the normal try
/catch
inside of async
functions.
这篇关于如何在 node.js 中使用 .then()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!