您好,我正在尝试使用 bing 搜索 API,我需要为字符串数组获取与来自 bing 的第一个结果的字符串相关的 URL。
目前 Promise.all 在 bingSearch 设置网站值之前解析,应该如何更改它以便在分配结果后获得日志?
在我的主要功能中
const suggestions = [{ suggestion: 'name1', rank: 62 }, { suggestion: 'name2', rank: 12 }]
async function bingWebSearch(query, i) {
await https.get({
hostname: 'api.bing.microsoft.com',
path: `/v7.0/search?q=${query}`,
headers: { 'Ocp-Apim-Subscription-Key': SUBSCRIPTION_KEY },
}, res => {
let body = ''
res.on('data', part => body += part)
res.on('end', () => {
suggestions[i].webpage = (JSON.parse(body)).webPages.value[0].url, { colors: false, depth: null }
})
res.on('error', e => {
console.log('Error: ' + e.message)
throw e
})
})
}
await Promise.all(suggestions.map(async (s, i) => await bingWebSearch(s.suggestion, i))).then(r => {
suggestions.map((s, i) => console.log(`
n${i+1}. ${s.suggestion} | ${s.rank} | ${s.webpage}
`))
}).catch(e => e.message)