因此,如果我setTimeout
在final上设置a console.log
,它将正常运行,但是我想我的新问题是,即使使用then
语句,为什么在解决所有问题后仍不触发它?
我有一个奇怪的错误,我无法弄清楚为什么它没有打印我期望的整个结构。我没有遇到任何错误,并且确实尝试输入了一些console.log
,但是似乎得到了anyOf
要记录的属性。它始终显示为空。
我的主要问题是hold
未正确记录。它显示anyOf
为空。
const $ = require('cheerio');
const Axios = require('axios').default;
let name = 'sqs';
let basePath = '/AWS_SQS.html'
let hold = {
'$schema': 'http://json-schema.org/draft-07/schema#',
'$id': `cf${name}`,
'description': `CF ${name}`,
'properties': {
'Type': {
'type': 'string',
'enum': [],
},
},
'anyOf': [] // this keeps coming up empty
};
let typeProperties = (t, p) => {
return {
'if': { 'properties': { 'Type': { 'const': t } } },
'then': {
'properties': {
'Properties': {
'type': 'object',
'properties': p,
},
},
},
}
}
const makeRequest = (bpath) => {
let url = 'https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/' + bpath
return Axios.get(url)
.then((res) => {
return res.data;
})
.catch(console.log);
};
let getData = makeRequest(basePath).then((data) => {
let match = $('.listitem>p>a', data);
match.map((i, e) => {
let t = $(e);
hold.properties.Type.enum.push(t.text());
makeRequest(t.attr('href')).then((newdata) => {
let holdProperties = {}
let pType = $($('.variablelist', newdata)[0])
$('.term>.code', pType).map((i, elem) => {
let propertyName = $(elem).text()
holdProperties[propertyName] = {}
})
hold.anyOf.push(typeProperties(t.text(), holdProperties))
}).catch(console.log)
});
}).catch(console.log)
getData.then(() => {
// Why doesnt this log fully once everything is resolved? If i put a setTimeout here, it will work fine
console.log(JSON.stringify(hold));
}).catch(console.log)
里面有相关的代码getData()
,你正在做makeRequest().then()
内部的.map()
,但完全无视该承诺makeRequest()
正在恢复。您不是在等他们。您需要使用它们Promise.all()
来等待所有这些,以便您可以返回与所有其他诺言完成有关的诺言。
您可以这样做:
let getData = makeRequest(basePath).then((data) => {
let match = $('.listitem>p>a', data).get();
return Promise.all(match.map(item => {
let t = $(item);
hold.properties.Type.enum.push(t.text());
return makeRequest(t.attr('href')).then((newdata) => {
let holdProperties = {}
let pType = $($('.variablelist', newdata)[0])
$('.term>.code', pType).map((i, elem) => {
let propertyName = $(elem).text()
holdProperties[propertyName] = {}
})
hold.anyOf.push(typeProperties(t.text(), holdProperties))
}).catch(err => {
console.log(err);
throw err; // propagate error back to caller
});
}));
}).catch(console.log)
getData.then(() => {
// Why doesnt this log fully once everything is resolved? If i put a setTimeout here, it will work fine
console.log(JSON.stringify(hold));
}).catch(console.log)
此代码中的更改:
.map()
添加return
,所以你必须return makeRequest(...)
让你.map()
将返回承诺的数组。.map()
使用return Promise.all(match.map(...))
,所以你在等待来自所有承诺.map()
等你回来的是总结的承诺。.get()
因此您可以对其使用真实的ES6迭代操作。.map()
匹配其array.map()
用途。注意,hold.anyOf
由于所有并行makeRequest()
调用都可以按任何顺序完成,因此数组的结果将没有保证的顺序。如果要按顺序排列它们,则应从.then()
处理程序中返回值,然后Promise.all()
按顺序累加所有值,然后可以从数组中使用它们,这些值是Promise.all()
按请求顺序排列后的值。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句