我有多个“
promise
”,我想一个接一个地运行,但我不确定是否要返回承诺,因为它变得非常混乱!
所以我决定使用
async
库并实现 parallel
方法。现在我注意到我所有的 Promise 都不是一个接一个地运行,而是在做 Promise 应该做的事情(无论什么时候运行 + 完成)。
我注意到所有 console.logs 在所有承诺完成之前都在运行。
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)。
就像 Bergi 所说,当你使用 Promise 时,
async.js
是多余的,你的代码可以简化为:
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') )
按照以下链接操作后我已经解决了这个问题..