Node.js中如何将Promise对象转为字符串?异步函数调用问题求助
解决Promise数组转字符串数组的问题
你的signToken函数返回的是Promise对象,用map遍历数组时,每个元素都是未完成的Promise,所以encodearray是Promise数组,而非字符串数组。要得到实际的字符串结果,需要等待所有Promise完成,具体修改如下:
方法一:使用Promise.all + await
因为你的usersdb已经是async函数,可以直接用await等待所有Promise resolve:
module.exports.usersdb = async function (req, res) { const arr = ["apple", "banana", "orange"]; // 等待所有signToken的Promise完成,得到字符串数组 const encodearray = await Promise.all(arr.map(data => _token.signToken(data))); console.log(encodearray); // 输出字符串数组:["token1", "token2", "token3"] }
方法二:将数组转为单个字符串(可选)
如果需要把整个数组合并成一个字符串,可使用join方法:
module.exports.usersdb = async function (req, res) { const arr = ["apple", "banana", "orange"]; const encodearray = await Promise.all(arr.map(data => _token.signToken(data))); const combinedString = encodearray.join(', '); console.log(combinedString); // 输出类似 "token1, token2, token3" }
原理说明
Promise.all会接收Promise数组作为参数,等待数组中所有Promise都成功resolve后,返回一个包含所有resolve结果的数组。此时encodearray就会是每个signToken返回的字符串组成的数组,而非Promise对象。
内容的提问来源于stack exchange,提问作者Alexandro Pineda
相关产品推荐
相关产品推荐

