欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

前端笔试题目合集(持续更新)

程序员文章站 2022-04-18 21:55:32
...

问答题

1.请使用Promise封装Ajax操作.
原始的Ajax操作如下:

var onSuccess = function(result){}; //成功的回调
var onFail = function(error){}; //失败的回调
var req = new XMLHttpRequest();
req.open("POST", "www.baidu.com", true);
req.onload = function(){
  if(req.readyState === 4 && req.status === 200){
    onSuccess(req.response);
  } else {
    onFail(req.statusText);
  }
}
req.onerror = function(){
  onFail(Error("网络异常"));
}

答案:

return new Promise(function(resolve, reject){
   var req = new XMLHttpRequest();
   req.open("POST", "<a href="http://www.baidu.com" target="_blank">www.baidu.com", true);
   req.onload = function(){
     if(req.readyState === 4 && req.status === 200){
       resolve(req.response);
     } else {
       reject(req.statusText);
     }
   }
   req.onerror = function(){
     reject(Error("网络异常"));
   }
 });
 

2.描述一下脚本

相关标签: 前端面试 面试