函数链接"/>
Node.js promise .then()与已定义函数链接
如何使用.then()
链接来调用Node.js中声明的函数?问题是在调用getFileType()
之后,我想调用getExif()
,但这会引发语法错误:
'use strict';
const FileType = require('file-type');
const exif = require('jpeg-exif');
const path = './alcatraz.jpg';
async function getFileType(filePath) {
return await FileType.fromFile(filePath);
}
function getExif(filePath) {
return new Promise((resolve, reject) => {
exif.parse(filePath, (error, result) => {
if(error) {
reject(error);
} else {
resolve(result);
}
});
});
}
getFileType(path).then((result) => {
console.log(result);
})
# ======> problem is here <======
.then(getExif(path) {
console.log(result);
})
.catch((error) => {
console.error(error.message);
process.exit(3);
});
语法错误是:
SyntaxError: missing ) after argument list
回答如下:您应该将呼叫返回到上方getExif(path)
内部的.then
,以便下方.then
可以使用它:
getFileType(path).then((result) => {
console.log(result);
return getExif(path);
})
.then((result) => {
console.log(result);
})
.catch((error) => {
console.error(error.message);
process.exit(3);
});
下部result
中的.then
变量将包含调用getExif
的结果。如果您希望getFileType
和getExif
都解析值,因为它们看起来并不相互依赖,请改用Promise.all
:
Promise.all([
getFileType(path),
getExif(path),
])
.then(([fileType, exif]) => {
// work with results
})
.catch((error) => {
console.error(error.message);
process.exit(3);
});
更多推荐
Node.js promise .then()与已定义函数链接
发布评论