javascript – Firefox:Promise.then不会异步调用

前端之家收集整理的这篇文章主要介绍了javascript – Firefox:Promise.then不会异步调用前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我阅读了Promise / A规范,它在2.2.4之下说:

onFulfilled or onRejected must not be called until the execution context stack contains only platform code

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

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

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

它在其他浏览器或使用ES6Promise-Polyfill时可以预期.

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

编辑:

它使用console.log工作,请参阅Benjamin Gruenbaum的回答:

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

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

output("First");

正如他在评论中指出的,这也发生在使用同步请求时,这正是您在测试场景中发生的原因.
我创建了我们测试中发生的最小例子:

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);
}

在Firefox中,这导致:

解决方法

这是因为您正在使用警报

当您在此处使用警报时,它将阻止所有投注关闭页面已冻结,执行停止,事情处于“平台级”.

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

如果您将该警报更改为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");

从我可以说,这实际上是permitted optional behavior

Optionally,pause while waiting for the user to acknowledge the message.

(重点是我)

基本上,firefox做的是这样的:

>执行直到遇到第一个警报.
>在暂停之前运行任何微任务完成(任务暂停,而不是微任务).
>然后作为一个微任务运行,所以“第二”被排队等候,并在警报之前.
>第二个警报运行.
>第一个警报运行.

令人困惑,但可以从我能说的话中得到.

原文链接:https://www.f2er.com/js/155290.html

猜你在找的JavaScript相关文章