gpt4 book ai didi

javascript - NodeJs 中的 UnhandledPromiseRejectionWarning : Unhandled promise rejection in _. 映射

转载 作者:行者123 更新时间:2023-12-04 09:30:13 24 4
gpt4 key购买 nike

当我运行下面的代码块时,我总是得到错误 -
UnhandledPromiseRejectionWarning:未处理的 promise 拒绝。此错误源于在没有 catch block 的情况下抛出异步函数内部或拒绝未使用 .catch() 处理的 promise 。要在未处理的 Promise 拒绝时终止 Node 进程,请使用 CLI 标志 --unhandled-rejections=strict (见 https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode)。 (拒绝编号:1)


module.exports = (app, spotifyAPI) => {

app.get('/api/search', requireLogin, async (req, res) => {

const URI_BASE = keys.ComputerVisionEndpoint + 'vision/v3.0/analyze';
const imageUrl = "https://upload.wikimedia.org/wikipedia/commons/3/3c/Shaki_waterfall.jpg"; // will be sent as req body
var results;

// making API call to microsoft cognitive services API
try {
results = await axios({
method: 'post',
url: URI_BASE,
headers: {
'Content-Type': 'application/json',
'Ocp-Apim-Subscription-Key' : keys.ComputerVision
},
params: {
'visualFeatures': 'Tags',
'details': '',
'language': 'en'
},
data: {
"url": imageUrl,
}
});
} catch (err) {
return res.status(400).send(err);
}

// remove the common ones - indoor, outdoor, ground, wall, person, woman, man, ceiling, floor
const to_filter = results['data']['tags'];
_.remove(to_filter, (item) => {
return (item.name === 'indoor' || item.name === 'outdoor' || item.name === 'ground' || item.name === 'wall'
|| item.name === 'person' || item.name === 'woman' || item.name === 'man' || item.name === 'ceiling'
|| item.name === 'floor'
);
});


// searching for relevant songs and adding them to the playlist
var id;
try {
id = await search_and_add(req, res, spotifyAPI, to_filter, playlist_id);
} catch (err) {
if (err['statusCode'] === 401) {
req.logout();
return res.redirect('/');
}
else {
return res.status(400).send(err);
}
}

});
}

search_and_add = async (req, res, spotifyAPI, to_filter, playlist_id) => {
_.map(to_filter, async (tag) => {
try {
const song_details = await spotifyAPI.searchTracks(tag.name, { limit: 1 });
//const song_uri = song_details['body']['tracks']['items'][0]['id'];
console.log(song_details);
} catch (err) {
throw err;
}
});
return;
// figure out where to re direct user
};
我很确定这是因为 search_and_add 函数中的 map 语句,但我不知道如何摆脱它并提供相同的功能来使 try-catch block 工作?有人可以帮忙吗?

最佳答案

您没有对 _.map(…) 的回调创建的 promise 做任何事情来电search_and_add .他们只是被忽略,不等待,并且在被拒绝时会引起警告。大概你打算使用 Promise.all那里?

function search_and_add(req, res, spotifyAPI, to_filter, playlist_id) {
return Promise.all(to_filter.map(async (tag) => {
// ^^^^^^^^^^^^
const song_details = await spotifyAPI.searchTracks(tag.name, { limit: 1 });
//const song_uri = song_details['body']['tracks']['items'][0]['id'];
console.log(song_details);
});
}

关于javascript - NodeJs 中的 UnhandledPromiseRejectionWarning : Unhandled promise rejection in _. 映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62876513/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com