[英]Promise return in while loop in node.js
我是node.js編程的新手。 我很困惑異步和等待如何工作
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始終是不確定的,我將如何以上述代碼或任何其他方式返回promise。
async
/ await
是鏈承諾功能的語法糖。 不要將其與基於回調的async.js
庫混淆,也不要在使用async.js
時使用后者-它們不能一起工作。 與其嘗試使用或多或少的適當回調來調用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};
}
(您也可以將其簡化為while (true) { …; if (…) return }
循環而沒有該dotill
變量)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.