我开始在 Node.js 中使用原始承诺和 async/await。
我有 2 个"promis-ified"函数,我想并行运行,then()
对结果执行一些操作并返回新数据。返回值始终是undefined
,但在.then()
内部,该值是我所期望的。
这是我的函数:
const fs = require('fs-promise-util').default;
/**
* compares 2 directories to find hooks of the same name
*
* @return {Array} hooks that exist in remote and local directories
*/
function remoteVSlocal () {
try {
Promise.all([
fs.readdir(REMOTE_HOOKS_PATH),
fs.readdir(LOCAL_HOOKS_PATH)
]).then(function ([REMOTE_HOOKS, LOCAL_HOOKS]) {
//filter out values that exist in both arrays
//this returns a new array with the values I expect
return LOCAL_HOOKS.filter(function (name) {
return REMOTE_HOOKS.includes(name);
});
});
} catch (err) {
return err;
}
}
当我调用该函数时,它返回undefined
:
console.log(remoteVSlocal());
我希望调用remoteVSlocal()
以返回Array.filter()
创建的新数组。
您的函数remoteVSlocal()
实际上并没有返回任何内容,这就是为什么返回值undefined
的原因。 您需要返回 promise 并在调用函数时使用该返回的承诺。 从嵌入式.then()
处理程序返回值不会从函数本身返回。
这是您的代码的工作版本,假设fs.readdir()
确实返回了一个承诺(顺便说一句,采用现有的标准 API 并更改其功能是一种可怕的做法 - 有更好的方法来承诺整个库)。
无论如何,这里有一些代码适合你:
function remoteVSlocal () {
return Promise.all([
fs.readdir(REMOTE_HOOKS_PATH),
fs.readdir(LOCAL_HOOKS_PATH)
]).then(function ([REMOTE_HOOKS, LOCAL_HOOKS]) {
//filter out values that exist in both arrays
//this returns a new array with the values I expect
return LOCAL_HOOKS.filter(function (name) {
return REMOTE_HOOKS.includes(name);
});
});
}
此外,您需要从remoteVSlocal()
返回承诺,然后使用返回的承诺:
remoteVSLocal().then(result => {
// use result here
}).catch(err => {
// process error here
});
更改摘要:
- 从
remoteVSlocal()
那里返回承诺 - 调用
remoteVSlocal()
时,将返回的承诺与.then()
一起使用,并.catch()
。 - 删除
try/catch
,因为此处没有同步异常。 承诺将通过被拒绝的承诺传播错误。