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

问题描述 投票:-1回答:1

这是我的节点js回调函数,我想改变这个函数来承诺。

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);

                       }
                   })
               }
           });
       }
    });

我想看看示例代码。

javascript node.js callback promise
1个回答
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);
});
© www.soinside.com 2019 - 2024. All rights reserved.