请考虑嵌套Promises
的以下结构:
const getData = async() => {
const refs = [{
name: "John33",
age: 33
},
{
name: "John34",
age: 34
},
{
name: "John35",
age: 35
},
{
name: "John36",
age: 36
}
];
let source = [{
name: "John30",
age: "unknown"
},
{
name: "John31",
age: "unknown"
},
{
name: "John32",
age: "unknown"
},
{
name: "John33",
age: "unknown"
},
{
name: "John34",
age: "unknown"
},
{
name: "John35",
age: "unknown"
}, {
name: "John36",
age: "unknown"
},
{
name: "John37",
age: "unknown"
},
{
name: "John38",
age: "unknown"
},
{
name: "John39",
age: "unknown"
}
];
const resolver = doc => {
return new Promise(doc => {
let clone = { ...doc
};
let found = refs.find(ref => {
return ref.name === doc.name;
});
if (found) clone.age = found.age;
return clone;
});
};
let getRefs = (doc, refs) => {
const promises = refs.map(r => {
resolver(doc).then(result => {
return result;
});
});
return Promise.all(promises);
};
let getCursorData = (cursor, refs, data) => {
const promises = cursor.forEach(doc => {
console.log("Getting cursor for " + doc.name);
let clone = { ...doc
};
return getRefs(clone, refs).then(result => {
console.log("Getting refs for " + clone.name);
data.push(result);
});
return;
});
return Promise.all(promises);
};
// Get data
let data = [];
await getCursorData(source, refs, data);
console.log("Returned data: ");
console.log(data);
return data;
};
console.log("Begin");
getData().then(result => {
console.log("End");
console.log(result)
});
由于某种原因,我没有到达代码的结尾({End
未打印)。我怀疑存在一些头寸或缺少回报,但是我陷入困境而找不到解决方案。
如何使此代码结构按预期工作,如下所示:
age
)此代码的预期结果是使用当前的Promise结构获取固定了可用引用的原始数据(source
):
[
name: "John30",
age: "unknown"
},
{
name: "John31",
age: "unknown"
},
{
name: "John32",
age: "unknown"
},
{
name: "John33",
age: 33
},
{
name: "John34",
age: 34
},
{
name: "John35",
age: 35
}, {
name: "John36",
age: 36
},
{
name: "John37",
age: "unknown"
},
{
name: "John38",
age: "unknown"
},
{
name: "John39",
age: "unknown"
}
]
答案 0 :(得分:0)
你去哪里!
std::move()