您如何仅在兑现承诺后才执行?
How do you only execute if the promise was fulfilled?
如果某些功能未按要求执行,我正在使用 promises 强制 NodeJS 停止 运行。目前,服务器会按要求停止,但如果函数成功实现了它们的承诺,我还想包含一个控制台日志。我正在使用 npm 'q' 模块。
工作代码
Q.all([
someFunction1(),
someOtherFunction('https://www.google.com', 'Google'),
someOtherFunction('https://www.facebook.com', 'Facebook'),
])
.catch(function (err){
console.log(err);
process.exit(1);
})
当按照下面添加 then 时,then 在承诺完成之前执行,因此无论承诺是履行还是拒绝,都会执行 console.log 调用。
Q.all([
someFunction1(),
someOtherFunction('https://www.google.com', 'Google'),
someOtherFunction('https://www.facebook.com', 'Facebook'),
])
.then(console.log("No problem here"))
.catch(function (err){
console.log(err);
process.exit(1);
})
您是就地调用 console.log
,因此无论承诺成功与否都会被调用。
将包含日志作为语句的函数传递给 .then
,只有在 Q.all(...)
成功时才会调用此函数:
.then(function () {
console.log("No problem here");
})
如果某些功能未按要求执行,我正在使用 promises 强制 NodeJS 停止 运行。目前,服务器会按要求停止,但如果函数成功实现了它们的承诺,我还想包含一个控制台日志。我正在使用 npm 'q' 模块。
工作代码
Q.all([
someFunction1(),
someOtherFunction('https://www.google.com', 'Google'),
someOtherFunction('https://www.facebook.com', 'Facebook'),
])
.catch(function (err){
console.log(err);
process.exit(1);
})
当按照下面添加 then 时,then 在承诺完成之前执行,因此无论承诺是履行还是拒绝,都会执行 console.log 调用。
Q.all([
someFunction1(),
someOtherFunction('https://www.google.com', 'Google'),
someOtherFunction('https://www.facebook.com', 'Facebook'),
])
.then(console.log("No problem here"))
.catch(function (err){
console.log(err);
process.exit(1);
})
您是就地调用 console.log
,因此无论承诺成功与否都会被调用。
将包含日志作为语句的函数传递给 .then
,只有在 Q.all(...)
成功时才会调用此函数:
.then(function () {
console.log("No problem here");
})