简体   繁体   English

了解 Node.js 中的.then() 行为

[英]Understanding of .then() behaviour in Node.js

Please correct me if I am wrong.如果我错了,请纠正我。

As per my understanding .then() will only execute once the dependent function finishes its task.根据我的理解.then()只会在依赖的 function 完成其任务后执行。 However here I could see different order of execution.但是在这里我可以看到不同的执行顺序。

Suppose array size is 20, console.log(i) (inside axios) prints in different order like 18, 12, 11,3,15... so on.假设数组大小为 20,console.log(i)(在 axios 内部)以不同的顺序打印,如 18、12、11、3、15... 等等。 using .then() can't we make it synchronous?.使用.then()我们不能让它同步吗?

I know adding await keyword in front of Axios would work perfectly.我知道在Axios前面添加await关键字会很好用。 But, just to make sure, is there any other way to achieve it?.但是,为了确保,还有其他方法可以实现吗?

Observed Behaviour.观察到的行为。

  1. When we execute this without await, this would work for few array items (it will be very fast).当我们在没有等待的情况下执行它时,这将适用于少数数组项(它会非常快)。
  2. When we execute using await keyword it will take too much time.当我们使用 await 关键字执行时,会花费太多时间。
var pdflist = ['one','two','three','four'.........'twenty']
for (let i=0; i<pdflist.length;i++)
{
            let uri = {
              method: 'GET',
              url:'https://pdffiles/'+pdflist[i]+'.pdf',
              responseType: "arraybuffer"
            };

            axios(uri).then(results => {
            console.log(i)                // prints in different order
            console.log(results)
            })
}

This is how you can solve the this issue with async and await .这就是您可以使用asyncawait解决此问题的方法。

const fn = async () => {
    var pdflist = ['one','two','three','four'.........'twenty']
    for (let i=0; i<pdflist.length;i++)
    {
        let uri = {
          method: 'GET',
          url:'https://pdffiles/'+pdflist[i]+'.pdf',
          responseType: "arraybuffer"
        };

        const result = await axios(uri)
        console.log(i)                // prints in different order
        console.log(results);
    }
}
fn()

Using Promise.all使用Promise.all

var pdflist = ['one','two','three','four'.........'twenty']
var promises = [];
for (let i=0; i<pdflist.length;i++)
{
    let uri = {
      method: 'GET',
      url:'https://pdffiles/'+pdflist[i]+'.pdf',
      responseType: "arraybuffer"
    };

    promises.push(axios(uri))
}

Promise.all(promises).then((allResults) => {
    allResults.forEach((res, i) => {
        console.log(i)                // prints in different order
        console.log(res);
    })
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM