如何在 node.js 中使用 .then()?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/49033694/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use .then() in node.js?
提问by anonymous
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:
我是node.js. 我刚刚读到我们可以使用.then()函数以特定顺序执行多个函数。我打算这样写代码:
function one(){
console.log("one")
}
function two(){
console.log("two")
}
function three(){
console.log("three")
}
one().then(two()).then(three())
But I'm getting this error:
但我收到此错误:
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
回答by Explosion Pills
.thenis 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
.then是一种存在于 Promise 上的方法,是一种代码同步机制。您的代码不是异步的,因此您不需要使用承诺。你可以打电话
one();
two();
three();
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.
如果您的代码执行异步操作,那么您可以使用 promises 和.then. 异步操作包括读/写文件、http 请求、计时器等等。
Just as an example, we can use the built in Promiseto create our own asynchronous operations:
举个例子,我们可以使用内置的Promise来创建我们自己的异步操作:
I don't recommend you do this normally. We're just using it as an example. In most cases you can call functions that already return promises for you.
我不建议您正常执行此操作。我们只是以它为例。在大多数情况下,您可以调用已经为您返回承诺的函数。
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());
Also note that when you use .then, you need to pass a callback. two()calls the twofunction immediately, so it's not the same as () => two().
还要注意,当你使用时.then,你需要传递一个回调。立即two()调用该two函数,因此它与() => two().
Next, you can often use async/awaitinstead of .thenwhich I think makes your code easier to reason about in most cases.
接下来,您可以经常使用async/await而不是.then我认为在大多数情况下使您的代码更容易推理的。
async function run() {
await one();
await two();
three();
}
run();
This is the same as the second example rewritten to use awaitinstead of .then. You can think of everything after awaitas being inside of a .thenchained to the expression after await.
这与重写为使用await而不是的第二个示例相同.then。您可以将 after 的所有内容await视为.then链接到 after 表达式的内部await。
Finally, you should handle errors by either chaining .catchto the promises or using the normal try/catchinside of asyncfunctions.
最后,您应该通过链接.catch到 Promise 或使用函数的正常try/catch内部来处理错误async。
回答by Dominic
.then only works if the function returns a Promise. Promises are used for asynchronous tasks, so you can wait on something before doing something else.
.then 仅在函数返回 Promise 时才有效。Promise 用于异步任务,因此您可以在做其他事情之前等待某事。
function one(){
return new Promise(resolve => {
setTimeout(() => {
console.log('one')
resolve();
}, 1000);
});
}
function two(){
return new Promise(resolve => {
setTimeout(() => {
console.log('two')
resolve();
}, 1000);
});
}
function three(){
return new Promise(resolve => {
setTimeout(() => {
console.log('three')
resolve();
}, 1000);
});
}
one().then(two).then(three);
You can use the resolve (and second argument reject) to return a result to the next .then or .catch:
您可以使用解析(和第二个参数拒绝)将结果返回到下一个 .then 或 .catch:
function one(){
return new Promise(resolve => {
setTimeout(() => {
resolve('one');
}, 1000);
});
}
function two(){
return new Promise(resolve => {
setTimeout(() => {
resolve('two');
}, 1000);
});
}
function three(){
return new Promise((resolve, reject) => {
setTimeout(() => {
reject(new Error('three'));
}, 1000);
});
}
one()
.then((msg) => {
console.log('first msg:', msg);
return two();
})
.then((msg) => {
console.log('second msg:', msg);
return three();
})
.then((msg) => {
// This one is never called because three() rejects with an error and is caught below.
console.log('third msg:', msg);
})
.catch((error) => {
console.error('Something bad happened:', error.toString());
});
回答by melvinv
Then is usually used in the context of Promises. You could start reading more about it here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then
然后通常用于 Promise 的上下文中。您可以在此处开始阅读更多相关信息:https: //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then
回答by federico scamuzzi
the .then() function is used for the PROMISE (so for async function ) when you need to KNOW WHEN IT'S FINISHED (and it is finished ok .. or KO ) ..so you have
.then() 函数用于 PROMISE(因此用于异步函数),当您需要知道它何时完成(并且它完成了 .. 或 KO )..所以你有
MYASYNCFUNCTION().then(function(response({
//do what you want when it's finish and everything ok .. with the result
}).catch(function(error){
// it's finshed but with error
})
IN your example .. you don't have .then() function cause they're simple function .. but if you want to have it (i don't know why . they've not async stuff inside .. but you can)
在你的例子中 .. 你没有 .then() 函数,因为它们是简单的函数 .. 但如果你想拥有它(我不知道为什么。他们里面没有异步的东西......但你可以)
so
所以
// install it via npm install promise
// 通过 npm install promise 安装
var Promise = require('promise');
function one(){
var promise = new Promise(function (resolve, reject) {
resolve('one');
});
});
}
and then
进而
one().then(function(resp){ console.log(resp) })
Hope it helps you!!
希望对你有帮助!!
回答by Alexander Kahoun
.then()is for Promises. You also want to pass the function, not its return type as the .then()parameter. To make your example work, try:
.then()是为了Promises。您还想传递函数,而不是它的返回类型作为.then()参数。要使您的示例工作,请尝试:
function one(){
return Promise.resolve(console.log("one"));
}
function two(){
return Promise.resolve(console.log("two"));
}
function three(){
return Promise.resolve(console.log("three"));
}
one()
.then(two)
.then(three)
.catch(error => {
console.error('uhoh');
});
Also, while this may work for your example. You won't normally use Promise.resolve(). You'll find it more typical to see the constructor used:
此外,虽然这可能适用于您的示例。您通常不会使用Promise.resolve(). 您会发现看到使用的构造函数更为典型:
function func(a, b) {
return new Promise((resolve, reject) => {
if (!a || !b) return reject('missing required arguments');
return resolve(a + b);
}
}
Calling rejecton an error condition, and resolveon success. Rejections are routed to the first .catch(). I encourage you to read up on Promises in the link above.
reject在错误条件和resolve成功时调用。拒绝被路由到第一个.catch()。我鼓励你在上面的链接中阅读关于 Promises 的内容。

