Node.js C并行不工作应该怎么办?

gcxthw6b  于 12个月前  发布在  Node.js
关注(0)|答案(1)|浏览(105)

我有多个promise ',我想一个接一个地运行,我不确定我想返回的承诺,因为它变得相当混乱!
所以我决定使用async库并实现parallel方法。现在我注意到我所有的promise都没有一个接一个地运行,相反,它们都在做promise应该做的事情(run + finish whenever)。
我注意到在所有的promise完成之前,所有的console.log都在运行。

async.parallel([
        (cb) => {
          console.log ("hi")
            grabMeData (Args)
              .then ( (data) => {

                // The promise is done and now I want to goto the next functio
                cb();
              }).catch(()=>console.log('err'));
        },
        (callback) => {
          // The above promise is done, and I'm the callback
          Query.checkUserExists()
          .then ( () => {
            if (Query.error) {
              console.log (Query.error); // Determine error here
              return; // Return to client if needed
            }
            callback();
          });
        },
        () => {
          // The above promise is done and I'm the callback!

          // Originally wanted to be async
          if (Query.accAlreadyCreated) {
            this.NewUserModel.user_id = Query.user_id;
            this.generateToken();
          } else {
            console.log ("account not created");
          }
          console.log ('xx')
        }
    ], () =>{
      console.log ("finished async parallel")
    });

任何原因,我的回调正在运行before的承诺是解决(.then)。

iaqfqrcu

iaqfqrcu1#

就像Bergi说的,async.js是多余的,当你使用promise时,你的代码可以简化为:

console.log('hi')
grabMeData(Args)
  .catch(e => console.error(e))
  .then(() => Query.checkUserExists())
  .then(() => {
    if (Query.accAlreadyCreated) {
      this.NewUserModel.user_id = Query.user_id
      return this.generateToken()
    } 
    console.log ("account not created")   
  })
  .then(() => console.log ('xx')  )

相关问题