【问题标题】:How can I change my callback function to promise?如何将我的回调函数更改为 promise?
【发布时间】:2018-05-30 10:37:32
【问题描述】:

这是我的node 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);

                       }
                   })
               }
           });
       }
    });

我想看示例代码。

【问题讨论】:

  • 我至少想试试看。
  • 你想做什么功能?

标签: javascript node.js callback promise


【解决方案1】:

假设 service.parseToCSV 和 Entry.insertPeople 返回承诺。

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

【讨论】:

  • 呃,但他们显然没有在 OP 示例中返回承诺?
  • 这是可怕的承诺代码,绝对没有使用链接。
  • 还有更多类似@bergi 的东西吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-12-12
  • 1970-01-01
  • 2018-11-09
  • 1970-01-01
  • 2015-12-11
  • 2018-02-08
  • 1970-01-01
相关资源
最近更新 更多