如何更改我的回调函数以承诺?

时间:2017-12-16 12:12:19

标签: javascript node.js callback promise

这是我的节点js回调函数,我想将此函数更改为promise。

service.parseToCsv('resources/' + peopleFileName, (err,people) => {
       if(err){
           res.status(400).send('ERROR TO PARSING CSV PEOPLES');
       } else{
           Entry.insertPeoples(people,(err,results) => {
               if(err){
                   let rmPath = 'resources/' + peopleFileName;
                   fs.unlink(rmPath);
                   res.status(400).send('ERROR TO INSERT PEOPLE DATA IN TO DATABASE');
               } else{
                   service.parseToCsv('resources/' + facilityFileName,(err,facilities) => {
                       if(err){
                           console.log(err);
                           res.status(400).send('ERROR TO PARSING CSV FACILITIES');
                       } else{

                           res.status(200).send(facilities);

                       }
                   })
               }
           });
       }
    });

我希望看到示例代码。

1 个答案:

答案 0 :(得分:1)

假设service.parseToCSV和Entry.insertPeople返回promises。

service.parseToCSV('resources/' + peopleFileName).catch(err => Promise.reject(new Error('PARSING CSV PEOPLES')))
.then(people => {
    return Entry.insertPeople(people).catch(err => Promise.reject(new Error('INSERT PEOPLE DATA IN TO DATABASE')));
})
.then(facilityFileName => {
    return service.parseToCSV('resources/' + facilityFileName).catch(err => Promise.reject(new Error('PARSING CSV FACILITIES')));
})
.then(facilities => {
    res.status(200).send(facilities);
})
.catch(err) => {
    console.log(err);
    res.status(400).send('ERROR TO '+err.message);
});