[英]Promise return in while loop in node.js
I am new to node.js programming . 我是node.js编程的新手。 I am confused how the async and await works
我很困惑异步和等待如何工作
const async = require('async');
createUser: async (user, myid) => {
let dotill = false;
let userid = null;
const getreturn = async.whilst(
function testCondition() { return dotill === false;},
async function increaseCounter(callback) {
let sr = "AB" + Math.floor(Math.random() * 99999999999) + 10000000000;
userid = sr.substr(0, 9);
await knex.raw('select * from userprofile where user_id=?', [userid]).then((res) => {
console.log(res.rowCount);
if (res.rowCount === 0) {
dotill = true;
callback;
}else{
callback;
}
});
},
function callback(err, n) {
if (err) {
return;
}
return {"done":true, "userid":userid}
}
);
console.log(getreturn);
// getreturn always undefined iam not getting and return
}
getreturn is always undefined how i will be able to return in above code or any other way to working in promise.. getreturn始终是不确定的,我将如何以上述代码或任何其他方式返回promise。
async
/ await
is syntactic sugar for functions that chain promises. async
/ await
是链承诺功能的语法糖。 Do not confuse it with the callback-based async.js
library, and don't use the latter when working with promises - they don't work together. 不要将其与基于回调的
async.js
库混淆,也不要在使用async.js
时使用后者-它们不能一起工作。 Instead of trying to call async.whilst
with more or less appropriate callbacks, just use a plain simple while
loop: 与其尝试使用或多或少的适当回调来调用
async.whilst
,不如使用简单的while
循环:
// const async = require('async'); // remove this!
async createUser(user, myid) {
let dotill = false;
let userid = null;
while (!dotill) {
const sr = "AB" + Math.floor(Math.random() * 99999999999) + 10000000000;
userid = sr.substr(0, 9);
const res = await knex.raw('select * from userprofile where user_id=?', [userid]);
console.log(res.rowCount);
if (res.rowCount === 0) {
dotill = true;
}
}
return {"done":true, "userid":userid};
}
(also you can simplify this to a while (true) { …; if (…) return }
loop without that dotill
variable) (您也可以将其简化为
while (true) { …; if (…) return }
循环而没有该dotill
变量)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.