如下面发布的代码所示,我正在返回一个Promise Form a函数.我希望在Promise解析时显示一条带有参数的文本消息.换句话说,对于以下代码行:

resolve("successfully saved the data to file:",{fileName+newExt})

当promise 被解析时,我收到了前面提到的文本,但没有`fileName+newExt‘的值.

我try 了以下几种方法:

resolve("successfully saved the data to file:",{d:fileName+newExt})
resolve("successfully saved the data to file:",fileName+newExt)

但始终显示文本,而不显示值fileName+ext

update

如下面发布的代码2部分所示,我知道如何在promise 解决时打印消息.但resolve()中的文本消息显示时不会显示值fileName+ext

code

export function writeToFile(fileName,contents,ext='.tiff') {
let newExt = ''
return new Promise((resolve,reject)=> {
    if (typeof (fileName) !== "string") {
        reject(new Error("fileName is not a string.Did you pass string-object using new String(..)"))
    }

    if (contents == undefined) {
        reject(new Error("contents to be written to the file is undefined"))
    }

    if (typeof (ext) !== "string") {
        reject(new Error("extension is not a string.Did you pass string-object using new String(..)"))
    }

    if (ext.charAt(0) === '.') {
        newExt = ext
    } else {
        newExt = '.' + ext
    }

    if (!fs.existsSync(envVars.DEBUG_OUTPUT_PATH_FOR_TIFFS)) {
        fs.mkdirSync(path, {recursive:true})
    }
    
    fs.writeFile(envVars.DEBUG_OUTPUT_PATH_FOR_TIFFS + fileName + ext, contents,{flag:'w'},(error)=> {
        if (error) {
            reject(new Error("error occured while writing data to file.error:",error," file:",fileName+newExt))
            throw error
        }
        resolve("successfully saved the data to file:",{d:fileName+newExt})
    });
})

}

code2

response.on('close', async()=>{
const bufferedData = Buffer.concat(data)
writeToFile("test", bufferedData,'.tiff')
.then(statusMsg => {
    console.log("write-to-file status message:", statusMsg)
    fromFile(envVars.DEBUG_OUTPUT_PATH_FOR_TIFFS + "test" + envVars.CONST_TIFF_EXT)
    .then(geoTIFF=> {
        geoTIFF.getImage()
        .then(geoTIFFImage=> {
            console.log("geoTIFFImage:",geoTIFFImage.getBoundingBox())
        })
    })
})

推荐答案

您不能从Promise解析多个值,这就是为什么您得不到文件字符串或对象的原因.

因此,您应该更改函数返回的结果.

例如,始终发送具有Message/Result/Error属性的对象

resolve({message:'msg'});

同样的道理适用于错误:

reject({message:error});

或者可能是一个数组或字符串,但只有一个参数.

请参阅:

How do you properly return multiple values from a Promise?

Can promises have multiple arguments to onFulfilled?

Javascript相关问答推荐

设置默认值后动态更新japbox或调色板

主要内部的ExtJS多个子应用程序

如何获取转换字节的所有8位?

fs. writeFile()vs fs.writeFile()vs fs.appendFile()

Javascript,部分重排序数组

Google图表时间轴—更改hAxis文本 colored颜色

docx.js:如何在客户端使用文档修补程序

Angular:动画不启动

colored颜色 检测JS,平均图像 colored颜色 检测JS

手机上的渲染错误文本必须在文本组件中渲染,但在浏览器上没有问题<><>

如何从隐藏/显示中删除其中一个点击?

在forEach循环中获取目标而不是父对象的属性

更改预请求脚本中重用的JSON主体变量- Postman

使用带有HostBinding的Angular 信号来更新样式?

是否可以在Photoshop CC中zoom 路径项?

从逗号和破折号分隔的给定字符串中查找所有有效的星期几

如何使用画布在另一个内部绘制一个较小但相同的形状,同时保持恒定的边界厚度?

如何更改Html元素S的 colored颜色 ,然后将其褪色为原始 colored颜色

如何通过Axios在GraphQL查询中发送数组

Angel Auth Guard-用户只有在未登录时才能访问登录页面,只有在登录时才能访问其他页面