如何使用已解决的Promise中的参数显示文本值。

huangapple go评论59阅读模式
英文:

how to display text value with argument from a resolved promise

问题

以下是翻译的代码部分:

如下所示的代码中我从一个函数中返回一个Promise当Promise解决时我想显示一个带参数的文本消息换句话说对于以下代码行

resolve("成功保存数据到文件:",{fileName+newExt})

当Promise解决时我收到上述文本但没有`fileName+newExt`的值

我尝试了以下方法

resolve("成功保存数据到文件:",{d:fileName+newExt})
resolve("成功保存数据到文件:",fileName+newExt)

但始终只显示文本而不显示`fileName+ext`的值

**更新**

如下面发布的code2部分所示我知道如何在Promise解决时打印消息但是`resolve()`中的文本消息显示时没有`fileName+ext`的值

**代码**

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.你是否使用new String(..)传递了字符串对象?"))
        }

        if (contents == undefined) {
            reject(new Error("要写入文件的内容未定义"))
        }

        if (typeof (ext) !== "string") {
            reject(new Error("扩展名不是字符串。你是否使用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, " 文件:", fileName + newExt))
                throw error
            }
            resolve("成功保存数据到文件:",{d:fileName+newExt})
        });
    })
}

**代码2**

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

as shown in the below posted code, i am returning a promise form a function.i would like to display a text message with argument when the promise is resolved. in other words, for the following line of code:

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

when the promise is resolved i receive the aforementioned text but without the value of `fileName+newExt'

i tried the following:

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

but the always the text gets displayed without the value of fileName+ext

update

as shown in code2 section posted below, i know how to print the message when the promise is resolved. but the text message in the resolve() gets displayed without the value of 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())
})
})
})

答案1

得分: 2

你不能从 Promise 中解析多个值,这就是你没有获取文件字符串或对象的原因。

因此,你应该更改从函数返回的结果。

例如,始终发送一个带有 message/result/error 属性的对象

resolve({message:'msg'});

错误情况也是一样的:

reject({message:error});

或者也可以使用数组或字符串,但只能是单个参数。

参考:

https://stackoverflow.com/questions/28703625/how-do-you-properly-return-multiple-values-from-a-promise

https://stackoverflow.com/questions/22773920/can-promises-have-multiple-arguments-to-onfulfilled

英文:

You cannot resolve multiple values from the promise, which is why you don't get file string, or object.

So, you should change the result returned from the function.

For example, always send an object with message/result/error property

resolve({message:'msg'});

the same goes for error:

reject({message:error});

or maybe an array, or string, but only a single argument.

see:

https://stackoverflow.com/questions/28703625/how-do-you-properly-return-multiple-values-from-a-promise,

https://stackoverflow.com/questions/22773920/can-promises-have-multiple-arguments-to-onfulfilled

答案2

得分: 1

你应该使用 [JavaScript 模板字符串][1]

```typescript
resolve(`成功将数据保存到文件:${fileName}${newExt}`)

如果因某些原因你无法使用模板字符串,可以使用 + 符号进行连接:

resolve("成功将数据保存到文件:" + fileName + newExt)

然后可以这样调用你的函数:

writeToFile(fileName, contents, '.tiff').then(console.log).catch(console.error);

你也不需要同时使用 rejectthrow。任何一个都会拒绝这个 promise,你可以像上面的示例那样使用 .catch((error) => console.error(error)) 来捕获错误。


<details>
<summary>英文:</summary>
You should use [JavaScript template literals][1]
```typescript
resolve(`successfully saved the data to file:${fileName}${newExt}`)

If for some reason you do not have access to template literals, use the + sign to concatenate:

resolve(&quot;successfully saved the data to file:&quot; + fileName + newExt)

You can then call your function as follows:

writeToFile(fileName, contents, &#39;.tiff&#39;).then(console.log).catch(console.error);

You also do not need to reject and to throw. Either one will reject the promise, and you can catch the error as shown on the example above with .catch((error) =&gt; console.error(error))

huangapple
  • 本文由 发表于 2023年6月29日 15:17:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/76578812.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定