为什么承诺在声明时执行? [英] Why do promises execute at the point of declaration?

查看:33
本文介绍了为什么承诺在声明时执行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用Promise.all()执行一组Promise.我的方法是将这些Promise放入数组中,然后将该数组传递给Promise.all().但是,我发现承诺一旦被声明就立即开始执行,甚至不等待Promise.all被调用.

I would like to execute a set of promises using Promise.all(). My approach is to put these promises in an array and then pass the array to Promise.all(). However, I find that the promises start executing as soon as they are declared and do not even wait for Promise.all to be called.

为什么会发生这种情况?我如何才能仅在调用Promise.all()时执行诺言?

Why is this happening and how can I have the promises only execute upon calling Promise.all()?

let promiseArray = [];
const values = [1, 2, 3, 4, 5];

values.forEach((value)=>{
  promiseArray.push(
    new Promise((resolve, reject)=>{
      console.log('value: ' + value);
      return resolve();
    })
  )
})


console.log('start')
Promise.all(promiseArray)

/*
 output is 

  value: 1
  value: 2
  value: 3
  value: 4
  value: 5
  start

 would have expected output to have been

  start
  value: 1
  value: 2
  value: 3
  value: 4
  value: 5
*/

推荐答案

将诺言视为执行中"使您感到困惑.一个承诺纯粹是一种通知机制.它通常与某些底层异步操作相关联,当您创建诺言时,通常会启动异步操作.

Thinking of promises as "executing" is getting you confused. A promise is purely a notification mechanism. It is typically tied to some underlying asynchronous operation and when you create the promise, the asynchronous operation is typically started.

Promise.all()跟踪您已经开始的一大堆异步操作何时完成(或以错误结束).

Promise.all() is then used to track when a whole bunch of asynchronous operations that you've already started have completed (or ended with an error).

因此,您无需使用 Promise.all()来开始一堆事情.您可以使用它来跟踪它们何时完成以及它们在代码中其他位置的启动时间.

So, you don't use Promise.all() to start a bunch of things. You use it just to track when they are all done and they are started elsewhere in your code.

当您使用 new Promise()手动创建一个Promise时,Promise执行程序将立即执行.这就是它们的设计方式.

When you manually create a promise with new Promise(), the promise executor is executed immediately. That's how they are designed.

如果您的诺言执行器中包含真正的异步操作,并且当这些操作完成时您正在执行 console.log(),则可能不会发现诺言的设计方式有任何问题.我认为您的大部分困惑是由于您的诺言执行者内部实际上没有任何异步操作而引起的,因此实际上甚至没有理由为此使用诺言.承诺旨在跟踪异步操作的完成.如果您没有实际的异步操作,则无需使用它们.

If you had real asynchronous operations in your promise executor and you were doing console.log() when those operations completed, you'd probably not find any issue with how promises are designed. I think most of your confusion stems from the fact that you don't actually have any asynchronous operation inside your promise executor and thus there's really no reason to even use a promise for that. Promises are designed to track the completion of asynchronous operations. No reason to use them if you don't have an actual asynchronous operation.

仅供参考,如果您希望将来在某个时候从Promise执行程序内部启动某些异步操作,则可以使用常规的 setTimeout() process.nextTick() setImmediate()操作,以安排该操作稍后开始.

FYI, if you want to start some asynchronous operation at some time in the future from inside the promise executor, you can use the normal setTimeout() or process.nextTick() or setImmediate() operations to schedule the operation to start later.

原本希望的输出是

would have expected output to have been

另外,您似乎希望输出的顺序严格. Promise.all()期望有N个并行运行的异步操作,并且对于这N个操作没有保证的完成顺序.相反, Promise.all()将跟踪所有结果,收集所有结果,并按顺序将结果数组呈现给 .then()处理程序(如果所有结果都已解析)成功地).它不会按顺序运行操作本身.这些操作并行运行,并以自然顺序完成.

Plus, it appears you are expecting your output to be in a strict order. Promise.all() expects there to be N asynchronous operations running in parallel and there is no guaranteed order of completion for those N operations. Instead, Promise.all() will track them all, collect all the results and present the .then() handler with an array of results in order (if they all resolved successfully). It does not run the operations themselves in order. The operations run in parallel and complete in whatever natural order they take.

这篇关于为什么承诺在声明时执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆