[英]How do I wait for a promise in loop to finish before do some other stuff?
I still confused about how to use promises. 我仍然对如何使用promises感到困惑。 I have a for loop call an asynchronous method which returns a value. 我有一个for循环调用一个返回值的异步方法。 I use this value to push into an array. 我用这个值推入一个数组。 But when I print the array it is empty. 但是当我打印数组时,它是空的。 Here is what I did: 这是我做的:
async function getLink(link) {
var browser = await puppeteer.launch({headless: true});
const page = await browser.newPage();
await page.goto(LINK)
const result = await page.evaluate( async() => {
let data = [];
const $ = window.$;
$('#gallery_01 .item').each(function(index, product) {
data.push($(product).find('a').attr('data-image'));
});
return data;
});
await browser.close();
return result;
}
var final = [];
for (var i = 0; i < 10; i++) {
var data = getLink(value[i].url).then(function(data) {
console.log(data); // urls show here
final.push(data);
});
}
Promise.all(final).then(() => {
console.log(final) // empty
})
The final
show empty. final
节目空了。 What did I do wrong with Promise? 我对Promise做了什么错? Pls help! 请帮忙!
I can't see what value
is, but it looks like it's supposed to be an array of objects with a url
property? 我看不出有什么value
,但看起来它应该是一个带有url
属性的对象数组?
Assuming the getLink() function is okay, try this for your loop: 假设getLink()函数没问题,请尝试以下循环:
const final = [];
for (var i = 0; i < 10; i++) {
final.push(getLink(value[i].url));
}
Promise.all(final)
.then(data => {
console.log(data);
});
Or a slightly more compact way of accomplishing the same thing: 或者是一种更紧凑的方式来完成同样的事情:
const promises = value.map(v => getLink(v.url));
Promise.all(promises)
.then(data => {
console.log(data);
});
Update: My bad, got a bit confused. 更新:我的不好,有点困惑。 The following code would only work without () =>
after the var fn
以下代码只能在var fn
之后不使用() =>
You are very close. 你很近。 Try this: 尝试这个:
var final = [];
var results = []; // you need a separate array for results
for (var i = 0; i < 10; i++) {
// renamed the variable, changed 'data' to 'fn'
var fn = () => getLink(value[i].url).then(function(data) {
console.log(data); // urls show here
results.push(data);
});
final.push(fn);
}
Promise.all(final).then(() => {
console.log(results)
})
Promise.all accepts an array of promises. Promise.all接受一系列承诺。 You have an array 'final' but seem to try to store the result of the fucntion execution as well as the function itself. 你有一个数组'final'但似乎试图存储fucntion执行的结果以及函数本身。
To do this correctly - first get an array of promises. 要正确地做到这一点 - 首先获得一系列承诺。 Then pass them to Promise.all(). 然后将它们传递给Promise.all()。
PS Assuming your function actually works, haven't looked at it, since the question was about promises. PS假设你的功能确实有效,没有看过它,因为这个问题是关于承诺的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.