简体   繁体   English

node.js-.then()未定义

[英]node.js - .then() is not defined

I'm using node.js + Express + sequelize for my API. 我正在为我的API使用node.js + Express + sequelize。 I have a post method where I use bulkcreate (to insert several rows at the same time to a table) but it makes an error: then is not defined. 我有一个post方法,在这里我使用bulkcreate(向一个表中同时插入几行),但是会出错:然后未定义。

This is my error: 这是我的错误:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>`enter code here`
</head>
<body>
<pre>ReferenceError: then is not defined<br> &nbsp; &nbsp;at router.post (C:\Users\Desktop\PROYECTOS\viajeros-api\routes\travellers.js:143:5)<br> &nbsp; &nbsp;at Layer.handle [as handle_request] (C:\Users\Desktop\PROYECTOS\viajeros
....
</body>
</html>

This is my post method: 这是我的张贴方法:

router.post('/:id/countries', (req, res) => {

  const travellerId = req.params.id;
  const registerJson = req.body;
    for(let i = 0; i < registerJson.length; i++) {
          models.travellers_countrie.bulkCreate([
            { traveller_id:travellerId, country_id:registerJson[i].id }
            ])
        };
    then(() => { 
      return models.travellers_countrie.findAll();
    }).then(paises => {
      console.log(paises)
    })
    .catch(error => {
      console.log('estamos en el error');
      console.log(error);
      let response = Errors.errorResponse(error);
      res.status(500).send(response);
    });
});

I can't solve the problem. 我无法解决问题。 Any idea to find the solution? 有找到解决方案的想法吗? thanks 谢谢

If you want to bulk edit then you should format data first, then update. 如果要批量编辑,则应首先格式化数据,然后再更新。 Using database operation in for loop is not good practice in your code 在for循环中使用数据库操作不是您的代码中的好习惯

Also, you are referring .then outside the for loop and your bulk insert function that's why its giving error. 同样,您在for循环和批量插入函数之外引用.then这就是其给出错误的原因。

Refer to this code, it should work now 参考此代码,它现在应该可以工作

const dataArray = [];

  for(let i = 0; i < registerJson.length; i++) {
    dataArray.push({ traveller_id:travellerId, country_id:registerJson[i].id })          
  };

 models.travellers_countrie.bulkCreate(dataArray)
    .then(() => { 
      return models.travellers_countrie.findAll();
    }).then(paises => {
      console.log(paises)
    })
    .catch(error => {
      console.log('estamos en el error');
      console.log(error);
      let response = Errors.errorResponse(error);
      res.status(500).send(response);
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM