JavaScript中的Promise顺序 [英] Order of promise in javascript

查看:41
本文介绍了JavaScript中的Promise顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我调用一个函数,该函数返回一个Promise对象,那么依次执行几次,这些异步操作的执行顺序是否与Promise对象的创建顺序相同?

If I call a function ,which returns a Promise object , sequentially several times would the order of execution of those async operations be same as the order in which Promise objects were created?

推荐答案

这取决于功能的实现以及执行这些异步操作"的含义.

It depends on the implementation of the function, and by what you mean by "the execution of those async operations."

通常,一个返回诺言的函数会同步启动一个异步操作,而这就是它的全部工作:启动.然后,该操作将继续并独立于启动它的功能而完成.

Typically, a function returning a promise synchronously starts an asynchronous operation, and that's all it does: Start the operation. The operation then continues and completes independently of the function that started it.

因此,如果您这样做:

var p1 = foo(1);
var p2 = foo(2);
var p3 = foo(3);

...和 foo 在调用时同步启动异步操作,然后是的,异步操作将按照创建承诺的顺序启动.

...and foo synchronously starts an asynchronous operation when you call it, then yes, the async operations will be started in the order the promises were created.

不是并不意味着它们按照该顺序继续或完成,实际上它们可能不会.这取决于有问题的操作.

That doesn't mean they continue or complete in that order, and indeed they very well may not. It depends on the operations in question.

示例:

function foo(value) {
  return new Promise(resolve => {
    console.log("starting " + value);
    setTimeout(function() {
      console.log("completing " + value);
      resolve(value);
    }, value == 2 ? 800 : 200);
  });
}
var p1 = foo(1);
var p2 = foo(2);
var p3 = foo(3);
// Naturaly, in real code, we'd have error handlers on those

foo 按顺序启动操作,但它们顺序混乱,因为 2 的操作要比 1 的操作花费更长的时间.和 3 .

foo starts the operations in order, but they complete out of order, because the operation for 2 takes longer than the operations for 1 and 3.

这篇关于JavaScript中的Promise顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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