我是异步编码的新手
我正在使用 csvtojson 库,我正在尝试转换csv文件并将结果传递给其他模块。
convert()函数如下所示:
convert: function (csvFilePath) {
return new Promise((resolve, reject) => {
const options = { delimiter: ["|",","],
noHeader: true ,
headers: ["header1", "header2"]
}
csv(options)
.fromFile(csvFilePath)
.on('end_parsed',(convertedJson) => {
resolve(convertedJson);
})
.on("done",(error) => {
reject(error);
})
});
}
我的电话:
const converter = require ("./converter")();
let json;
json = converter.convert("./importSample.csv");
console.log(json);
当我执行代码时,我可以看到承诺仍处于暂挂状态:
Promise { <pending> }
我认为我必须使用.then()
函数,但我不知道在哪里或如何。
答案 0 :(得分:4)
从converter
函数获得承诺,该对象具有方法then
。你应该这样做。
const converter = require ("./converter")();
converter.convert("./importSample.csv").then(json => {
console.log(json);
}).catch(error => {
console.log(error);
});
答案 1 :(得分:1)
Promise有一个固定的语法架构。我将用一个简单的代码解释它。
var x = new Promise((resolve,reject)=>{
//here you perform an asynchronous call
resolve(value); //receive it in 'then' part of promise
reject(error): //if your operation fails due to any error, you call reject, which is handled by 'catch' part of the promise.
});
x.then((value)=>{
//this is the part which was called using resolve, and the value it receives is the value you passed as argument in resolve.
});
x.catch((error)=>{
//this part is called by reject. the error received is the value you passed inside the reject.
});
所以,你的功能应该像 -
converter.convert("./importSample.csv").then((json)=>{
//here is your part of code which is to be handled synchronously after the promise is called.
}).catch((error)=>{
//in case any error occurs and you want your program to exit gracefully.
});