我所知道的setTimout
比Promise
晚
所以我想证明那是真的。
我在setTimeout
元素中设置了script
,并在React.componentDidMount
中请求使用axios
和async await
语法糖。
但是结果是setTimtout
是console
之前的didMount
。我不知道为什么。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>order?</title>
</head>
<body>
<div id="app"></div>
<div>
<h2>order list</h2>
<ol id="ol">
</ol>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.min.js"></script>
<!-- <script src="https://cdn.bootcss.com/react/16.8.6/umd/react.production.min.js"></script>-->
<!-- <script src="https://cdn.bootcss.com/react-dom/16.8.6/umd/react-dom.production.min.js"></script>-->
<script src="https://cdn.bootcss.com/react/15.4.2/react.min.js"></script>
<script src="https://cdn.bootcss.com/react-dom/15.4.2/react-dom.min.js"></script>
<script>
window.olElement = document.getElementById('ol');
function createElement(text) {
const element = document.createElement('li')
element.innerText = text;
return element;
}
async function getData() {
await axios('https://www.apiopen.top/weatherApi?city=%E5%8C%97%E4%BA%AC').then(() => {
olElement.appendChild(createElement("axios then in script element"))
});
olElement.appendChild(createElement("await res in script element"))
}
setTimeout(() => {
olElement.appendChild(createElement("setTimeout in script element"))
});
getData();
</script>
<script>
function _instanceof(left, right) {
if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
return right[Symbol.hasInstance](left);
} else {
return left instanceof right;
}
}
function _typeof(obj) {
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
_typeof = function _typeof(obj) {
return typeof obj;
};
} else {
_typeof = function _typeof(obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
}
return _typeof(obj);
}
function _classCallCheck(instance, Constructor) {
if (!_instanceof(instance, Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _possibleConstructorReturn(self, call) {
if (call && (_typeof(call) === "object" || typeof call === "function")) {
return call;
}
return _assertThisInitialized(self);
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
var A =
/*#__PURE__*/
function(_React$Component) {
_inherits(A, _React$Component);
function A() {
_classCallCheck(this, A);
return _possibleConstructorReturn(this, _getPrototypeOf(A).apply(this, arguments));
}
_createClass(A, [{
key: "componentDidMount",
value: async function componentDidMount() {
olElement.appendChild(createElement("react componentDidMount"))
var res = await axios('https://www.apiopen.top/weatherApi?city=%E5%8C%97%E4%BA%AC').then(res => {
olElement.appendChild(createElement("axios then in react didMount"))
return res
});
olElement.appendChild(createElement("await res in react didMount"))
}
}, {
key: "render",
value: function render() {
return React.createElement("div", null, "A");
}
}]);
return A;
}(React.Component);
ReactDOM.render(React.createElement(A, null), document.getElementById('app'));
</script>
</body>
</html>
答案 0 :(得分:0)
说setTimeout的运行时间比promise晚,这有点令人困惑,因为它们都是异步的,并且会等到他们需要完成任务的时间。
在这种情况下,立即运行setTimeout且不延迟将回调置于事件队列中。在将setTimeout从事件队列中移除并运行之前,浏览器将处理当前函数中的所有代码。
Axios向apiopen发出HTTP请求。承诺只会在请求完成后才能解决,这需要一些时间,例如大约500毫秒左右(您可以在开发工具的网络面板中检查多长时间)。您的其他代码将继续运行,包括setTimeout事件,直到http请求完成。
从本质上讲,promise是编写回调的一种更好的方法,但是真正需要时间的是您正在等待的异步任务。
MDN在using Promises上拥有大量资源。如果您有兴趣了解为什么稍后不延迟运行setTimeout,请查看Concurrency model and the Event Loop
答案 1 :(得分:0)
您的测试用例与您要测试的内容无关。通过使用axios
,您实际上将HTTP请求放入Promise中,并且Promise的解析时间现在取决于请求完成的时间。
对于无偏见的测试用例,请在Promise和setTimeout内部使用相同的功能,例如this question.