return 值是 undefined.Could 告诉我应该怎么做才能修复它?
The return value is undefined.Could tell what should I do to fix it?
The value of store is undefined.colud tell me what I did wrong.
Should I use Async and await or Promise ?
var store = db.read(collectionName, (status, data) => {
//database read function
if (status) {
names.listOfData = data;
var send = names;
console.log("send---->", send); // send value here is what I need to return.
return send; // Getting required data for send. Problem here is returning it and storing it in store.
} else {
return null;
}
});
console.log("store-->", store);
Here value of store is Undefined. No proper return
您无法写入要存储的结果并在 db.read
之后立即看到它,因为 db.read
不会等待回调完成并且不会 return 来自它作为 return 值。
您应该将此调用包装到 new Promise
。它可能看起来像这样:
var store = await (new Promise(resolve, reject) => {
db.read(collectionName, (status, data) => {
//database read function
if (status) {
names.listOfData = data;
var send = names;
console.log("send---->", send); // send value here is what I need to return.
resolve(send);
} else {
resolve(null);
}
});
});
请阅读有关异步函数的更多信息,async/await
、Promise
以及如何将带有回调的函数转换为异步函数。
The value of store is undefined.colud tell me what I did wrong. Should I use Async and await or Promise ?
var store = db.read(collectionName, (status, data) => {
//database read function
if (status) {
names.listOfData = data;
var send = names;
console.log("send---->", send); // send value here is what I need to return.
return send; // Getting required data for send. Problem here is returning it and storing it in store.
} else {
return null;
}
});
console.log("store-->", store);
Here value of store is Undefined. No proper return
您无法写入要存储的结果并在 db.read
之后立即看到它,因为 db.read
不会等待回调完成并且不会 return 来自它作为 return 值。
您应该将此调用包装到 new Promise
。它可能看起来像这样:
var store = await (new Promise(resolve, reject) => {
db.read(collectionName, (status, data) => {
//database read function
if (status) {
names.listOfData = data;
var send = names;
console.log("send---->", send); // send value here is what I need to return.
resolve(send);
} else {
resolve(null);
}
});
});
请阅读有关异步函数的更多信息,async/await
、Promise
以及如何将带有回调的函数转换为异步函数。