Firefox:Promise.then不是异步调用的

sir*_*ion 10 javascript firefox promise

我阅读了Promise/A +规范,它在2.2.4下说:

在执行上下文堆栈仅包含平台代码之前,不得调用onFulfilled或onRejected

但是在Firefox(我测试了38.2.1 ESR和40.0.3)中,以下脚本同步执行onFulfilled方法:

var p = Promise.resolve("Second");
p.then(alert);
alert("First");
Run Code Online (Sandbox Code Playgroud)

(它似乎没有使用警报运行,它也可以在这里尝试:http://jsbin.com/yovemaweye/1/edit?js,output)

它在其他浏览器或使用ES6Promise-Polyfill时可以正常工作.

我在这里错过了什么吗?我总是认为then-method的一个要点是确保异步执行.

编辑:

它在使用console.log时有效,请参阅Benjamin Gruenbaum的回答:

function output(sMessage) {
  console.log(sMessage);
}

var p = Promise.resolve("Second");
p.then(output);

output("First");
Run Code Online (Sandbox Code Playgroud)

正如他在评论中指出的那样,这也发生在使用同步请求时,这正是它在测试场景中发生的原因.我创建了一个关于测试中发生的事情的最小例子:

function request(bAsync) {
  return new Promise(function(resolve, reject) {
    var xhr = new XMLHttpRequest();
    xhr.addEventListener("readystatechange", function() {
      if (xhr.readyState === XMLHttpRequest.DONE) {
        resolve(xhr.responseText);
      }
    });
    xhr.open("GET", "https://sapui5.hana.ondemand.com/sdk/resources/sap-ui-core.js", !!bAsync);
    xhr.send();
  });
}

function output(sMessage, bError) {
  var oMessage = document.createElement("div");
  if (bError) {
    oMessage.style.color = "red";
  }
  oMessage.appendChild(document.createTextNode(sMessage));
  document.body.appendChild(oMessage);
}

var sSyncData = null;
var sAsyncData = null;

request(true).then(function(sData) {
  sAsyncData = sData;
  output("Async data received");
});

request(false).then(function(sData) {
  sSyncData = sData;
  output("Sync data received");
});


// Tests
if (sSyncData === null) {
  output("Sync data as expected");
} else {
  output("Unexpected sync data", true);
}
if (sAsyncData === null) {
  output("Async data as expected");
} else {
  output("Unexpected async data", true);
}
Run Code Online (Sandbox Code Playgroud)

在Firefox中,这导致:

在此输入图像描述

Ben*_*aum 10

这是因为你正在使用 alert

当你alert在这里使用时它会阻止所有的赌注 - 页面已经冻结,执行暂停,而且事情处于"平台级别".

它可能被认为是一个错误,它肯定不是我所期望的 - 但核心是关于alertJavaScript任务/微任务语义之间的不兼容性.

如果您将该警报更改为console.log或附加到document.innerHTML您,您将得到您期望的结果.

var alert = function(arg) { // no longer a magical and blocking operation
  document.body.innerHTML += "<br/>" + arg;
}

// this code outputs "First, Second, Third" in all the browsers.

setTimeout(alert.bind(null, "Third"), 0);

var p = Promise.resolve("Second");
p.then(alert);

alert("First");
			
 
Run Code Online (Sandbox Code Playgroud)

据我所知,这实际上是允许的可选行为:

(可选)在等待用户确认消息时暂停.

(强调我的)

基本上,firefox的作​​用是:

  • 执行直到遇到第一个alert.
  • 在暂停之前运行任何微任务完成(任务暂停,而不是微任务).
  • then作为微任务运行,因此"第二个"排队等候alert.
  • Second警报被运行.
  • First警报被运行.

令人困惑,但允许从我所知道的.