如何获取具有回调的内置方法的映射值



我有一些函数需要得到值并返回它,但在这些函数中,有一些数组和内部的映射,我需要调用内置函数里面有回调。

代码如下:

const db = require('db')
function test(){
let arr = [1,2,3,4,5]
let result = []
arr.map(function (val, idx){
db.get(key, function (err, value) {
//how can i get all value and passing it to result variable and passing the result to become return value in test() function ?
// db.get() is only return true, not return any other value
}
})
}

如何获取数据并返回redisGetAll函数..

我已经做的是:

const db = require('db')
function test(){
let arr = [1,2,3,4,5]
let result = []
arr.map(function (val, idx){
db.get(key, function (err, value) {
result.push({key, value})
}
})
return result //this should be still empty array, cause result.push happen in async process, 
}

我知道我不能给data变量赋值,因为这是回调异步的,第一次初始化时它仍然是空数组。

您应该遵循以下异步等待方法

const db = require('db')
async function test() {
const arr = [1, 2, 3, 4, 5]
return await Promise.all(arr.map(async (val, idx) => getObj(key)));
}
function getObj(key) {
return new Promise(function(resolve) {
db.get(key, function(err, value) {
resolve({
key,
value
});
});
});
}

我假设你知道key变量来自哪里。另一方面,记住函数test必须在等待await test()

时调用

最新更新