While I thought I was using Async and Await keywords properly, it appears as though I am doing something wrong.
(当我以为我正确使用了Async和Await关键字时,好像我做错了什么。)
I am using PouchDB, which is a great Javascript database that syncs with CouchDB.
(我正在使用PouchDB,这是一个与CouchDB同步的出色Javascript数据库。)
PouchDB uses promises for many of its functions, and has native support for Async and Await.(PouchDB的许多功能都使用了promises,并且对Async和Await具有本机支持。)
As an example, to retrieve the basic information about a database, you would use the following code:(例如,要检索有关数据库的基本信息,可以使用以下代码:)
db.info().then(function (info) {
console.log(info);
})
I understand this, and it works.
(我了解这一点,并且有效。)
But if I try and put this inside a function, and then call that function, things go haywire.(但是,如果我尝试将其放在一个函数中,然后调用该函数,事情就会变得一团糟。)
And I'm sure it's me and not PouchDB that is the problem...(而且我确定是问题所在,而不是PouchDB。)
function getLocalDBInfo(db){
try {
db.info().then(function (info) {
return info;
});
} catch (error) {
console.log("can't get local DB info: ", error);
}
}
async function testing(db){
try {
var info=await getLocalDBInfo(db);
await console.log("DB info=", info);
await console.log("Doc count= ", info.doc_count);
}
catch(err){
console.log("error=",err);
}
//info contains...
//{"doc_count":0,"update_seq":0,"db_name":"kittens"}
}
testing(MY_db);
If I log info
inside the getLocalDBInfo
function, it eventually (ie. after the promise fulfills) logs info
to the console.
(如果我在getLocalDBInfo
函数中记录info
,它最终(即在诺言履行后)会将info
记录到控制台。)
But, the logs inside the testing
function return immediately with undefined
.(但是, testing
函数中的日志立即返回undefined
。)
It makes sense to me that they are returning undefined
because they are returning immediately, but I was trying to have them wait for info
by using async
and await
.(对我来说,它们返回undefined
是有道理的,因为它们会立即返回,但是我试图通过使用async
和await
来让它们等待info
。)
Any suggestions as to what I am doing wrong?(关于我在做什么错的任何建议吗?)
ask by robert smith translate from so
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…