Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/467.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使异步代码像同步Javascript一样工作_Javascript_Node.js_Asynchronous_Promise - Fatal编程技术网

使异步代码像同步Javascript一样工作

使异步代码像同步Javascript一样工作,javascript,node.js,asynchronous,promise,Javascript,Node.js,Asynchronous,Promise,我正在使用nodejs 这是我的名为createSchema的函数: const createSchema = () => { Business.findAll({ raw: true, }).then((data) => { data.forEach((client) => { postgresDB.createSchema(client.code).then(() => { Object.keys(postgresD

我正在使用nodejs

这是我的名为createSchema的函数:

const createSchema = () => {
  Business.findAll({
    raw: true,
  }).then((data) => {
    data.forEach((client) => {
      postgresDB.createSchema(client.code).then(() => {
        Object.keys(postgresDB.models).forEach((currentItem) => {
          postgresDB.models[currentItem].schema(client.code).sync();
        });
        console.log('Postgres schema created');
      }).catch(() => {
      });
    });
  }).catch((err) => {
    console.log('Warning:', err.message);
  });
};
createSchema();
我正在调用这个函数,在这个post函数中

exports.createBusiness = (req, res) => {
  const business = {
    name: req.body.name,
    code: req.body.code,
    email: req.body.email,
  };
  Business.create(business)
    .then((rawbusinessData) => {
      createSchema()     // this is the function
        .then(() => { .  // i want to complete createSchema fully then only i want to execute this below stuffs
          const businessData = rawbusinessData.get({ plain: true });
          const loginDetails = {
            username: 'sameer',
            password: encrypt('sameer'),
          };
          const schemaLogin = postgresDB.models.login.schema(businessData.code);
          schemaLogin.create(loginDetails).then((loginData) => {
            console.log('loginData:', loginData);
          });
          res.status(200).send(businessData);
        });
    })
    .catch((err) => {
      console.log('err:', err);
    });
};
我正在调用第二个post函数中的第一个函数,该函数名为createBusiness

我想完全完成createSchema函数,然后只需要在第二个名为createBusiness的函数中执行其他thenmethod()

看我的代码,我做了一个评论,需要先处理一下


我尝试了异步等待,但没有工作

理想情况下,巡更代码应该有效。出现此问题的原因可能是
createSchema()
函数未返回承诺

     const createSchema = () => {
      Business.findAll({
        raw: true,
      }).then((data) => {
        data.forEach((client,index) => {

          postgresDB.createSchema(client.code).then(() => {
            Object.keys(postgresDB.models).forEach((currentItem) => {
              postgresDB.models[currentItem].schema(client.code).sync();
               if(index==data.length-1)
                return true;
            });
            console.log('Postgres schema created');
          }).catch(() => {
          });
        });
      }).catch((err) => {
        console.log('Warning:', err.message);
      });
    };

你错过了很多地方的承诺。您需要返回所有这些文件:

// No "block" implies return
const createSchema = () =>
  Business.findAll({ raw: true})
    .then((data) => 
      // wrap Promise.all and map() instead of forEach()
      Promise.all(
        data.map((client) =>
          postgresDB.createSchema(client.code).then(() => 
            // Again wrap Promise.all and map()
            Promise.all(
              Object.keys(postgresDB.models).map((currentItem) => 
                postgresDB.models[currentItem].schema(client.code).sync()
              )
            )
          )
        )
      )
    )
    .then(() => console.log("now I'm done"))
    //.catch((err) => console.log('Warning:', err.message));
因此,大多数情况下,包装并使用它来实际返回您正在迭代的承诺


另一件事是不要过度使用块
{}
。只要返回箭头函数就可以了,反正里面只有一样东西。可以选择删除
.catch()
,只允许抛出此函数中的错误。调试之后,您实际上“应该”删除该行并允许抛出错误。

返回Business.findAll({
.Missing returnIs
postgresDB.models[currentItem].schema(client.code).sync()
一个同步操作,还是它返回了一个在运行底层代码之前需要解决的
承诺?它返回了一个承诺,我想是的!我仍然认为它没有像我预期的那样工作。@Neillun从createSchema返回承诺(将返回添加到方法的开头)。createSchema的代码已经在问题中。还值得指出的是,一旦createSchema返回承诺,async/await也将起作用。我编辑了答案,看看它是否起作用。其目的是检测循环结束并返回承诺。在createSchema()之后的第二个函数中,按照下面的方式修改代码,然后方法不起作用。const createSchema=async()=>{}change函数返回一个promise。第二个函数仍然首先执行,它不会等待第一个函数完全完成。谢谢您的回答,但仍然是以下代码:schemaLogin.create(loginDetails)。然后((loginData)=>{console.log('loginda:',loginda);});首先执行!@MohamedSameer确实要执行吗?在createSchema中也放一个log语句。可能它只是返回一些您不期望的内容。@MohamedSameer您指向的代码在
then()之后
附加在您的列表中此函数的末尾。我只是为您输入了一个
日志
,以便您可以复制该日志,并确定此代码何时完成。我假设一切都是承诺,只返回“每一个”函数调用。其他任何东西都不可能先触发。除非你也破坏了你发布的代码。@NeilLunn消息“现在我完成了”它没有显示在我的服务器上。@MohamedSameer什么消息?这甚至不在您的代码中。这里的最大问题是您不明白何时需要返回已评估的承诺。我当然不相信您神奇地知道如何在代码的其他地方执行此操作。不要运行任何其他代码。只运行您实际要求的一个函数关于。我不会整夜坐在这里调试你的整个程序。测试一个函数,然后分别解决剩下的问题。