Node.js promise .then()与已定义函数链接

编程入门 行业动态 更新时间:2024-10-27 22:34:31

Node.js promise .then()与已定义<a href=https://www.elefans.com/category/jswz/34/1771370.html style=函数链接"/>

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的结果。如果您希望getFileTypegetExif都解析值,因为它们看起来并不相互依赖,请改用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()与已定义函数链接

本文发布于:2024-05-07 03:38:33,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1754201.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   定义   链接   Node   js

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!