如何在循环函数中解决承诺
我正在尝试发出多个异步请求,然后使用for循环将获得的数据推入数组。但是,我遇到了一个问题,即forloop本身不会返回解决promise所需的值。因此,如何在for循环中完成promise并确保在为GET方法呈现它之前填充数组。对不起,我的英语不好。我对异步概念还是陌生的,如果可能,请用简单的语言教我。另外,如果有更好的方法可以解决我想知道的问题。
const currencyName = ["btc", "eth", "xrp"];
let dataCollections = [];
for (i = 0; i < currencyName.length; i ++) {
dataCollections.push(new Promise(function(resolve, reject) {
request.get(`/${currencyName[i]}jpy`, function(error, response, body) {
if (error) {
reject(error);
} if (dataCollections.length === 3) {
dataColletions = [];
} else {
resolve(JSON.parse(body));
}
});
}));
}
//Promise.all(??).then(??)
//For rendering dataCollections
app.get("/", function(req, res) {
res.render("home", {dataCollections: dataCollections});
}
回答如下:1)考虑将数组currencyNames
命名为复数,以便您可以为迭代器currencyName
命名。
2)您的for循环正在重新发明array.map
函数。考虑改用array.map
。
3)您的for循环有一个不可能的if子句(if (dataCollections.length === 3)
),这也意味着else子句在错误的if语句上。我认为这是一个错字。
现在是您的问题的核心,是Proimse.all(Array<Promise>)
是您想要的;当其参数中的所有元素都解析后,它就会解析。
const currencyNames = ["btc", "eth", "xrp"];
let dataCollections = currencyNames.map(currencyName => new Promise((resolve, reject) =>
request.get(`https://apiv2.bitcoinaverage/indices/global/ticker/${currencyName}jpy`, (error, response, body) => {
if (error)
reject(error);
else
resolve(JSON.parse(body));
})));
//For rendering dataCollections
app.get("/", async (req, res) =>
res.render("home", {dataCollections: await Promise.all(dataCollections)}));
与本文相关的文章
评论列表(0)
- 暂无评论