简体   繁体   English

在做其他一些事情之前,我如何等待循环中的承诺完成?

[英]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.

相关问题 在 Mongoose 中呈现页面之前,如何等待带有回调 function 的 for 循环完成 - How do I wait for a for loop with a callback function inside to finish before I render a page in Mongoose 异步for循环:如何使for循环等待函数完成? - Asynchronous for loop: how do I make the for loop wait for function to finish? 如何等待Promise.all中的Promise.all中的2个完成并执行其他任务 - How to wait for 2 of Promises in Promise.all to finish and then do another task 我如何等待promise的“ then”块在嵌套的forEach循环中执行,然后再次循环? - How do I wait for a promise's “then” block to execute within nested forEach loops before the loops iterate again? 如何等待exec在路由器中完成? - How do I wait on exec to finish within my router? 如何在 Jest 中等待 exec 进程完成? - How do I wait for an exec process to finish in Jest? 在使用Mongoose和MongoDB的API端点中,如何在返回响应给客户端之前等待所有数据库查询完成 - In an API endpoint using Mongoose and MongoDB, how do I wait for all database queries to finish before returning a response to the client 如何在node.js中等待N个异步函数完成,以便对它们的所有组合结果进行一些工作? - How to wait for N number of async functions to finish in node.js so that I can do some work on all their combined results? 在退出循环之前,如何等待直到循环中的异步过程完成? - How do I wait until an asynchronous process inside a loop is finished before exiting the loop? 我如何在继续执行之前等待Javascript同步循环中的异步回调完成 - How can I wait for asynchronous callback inside Javascript synchronous loop to finish before proceeding
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM