[英]Node.js Can't fulfill promise (Promise { <pending> })
I m new in asynchronous coding 我是异步编码的新手
I m using csvtojson library and I'm trying to convert a csv file and pass the result in an other module . 我正在使用csvtojson库,并且试图转换一个csv文件并将结果传递到另一个模块中。
The convert() function looks like this: 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);
})
});
}
My call: 我的电话:
const converter = require ("./converter")();
let json;
json = converter.convert("./importSample.csv");
console.log(json);
When I execute the code I can see that the promise is still on pending state: 当我执行代码时,我可以看到Promise仍处于待处理状态:
Promise { <pending> }
I think that I have to use the .then()
function but I don't know where or how. 我认为我必须使用.then()
函数,但是我不知道在哪里或如何使用。
From converter
function you are getting promise, and that object has method then
. 从converter
的功能你得到的许诺,对象有方法, then
。 You should do something like this. 你应该做这样的事情。
const converter = require ("./converter")();
converter.convert("./importSample.csv").then(json => {
console.log(json);
}).catch(error => {
console.log(error);
});
Here you can find nice tutorial about Promises, and here is documentation for Promises. 在这里您可以找到有关Promises的不错的教程, 这是Promises的文档。
Promise has a fixed syntactical architecture. Promise具有固定的语法体系结构。 I'll explain it with a simple code. 我将用一个简单的代码来解释它。
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.
});
So , your function should go something like- 因此 ,您的功能应类似于:
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.
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.