当前位置: 首页 > news >正文

promise使用

1.获取promise的返回结果的正确写法:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
</head>
<body>
<script   type="text/javascript">function foo() {return new Promise((resolve, reject) => {resolve('hello world!')});}p = foo()
p.then(result => console.log(result)) // "hello world!"</script></body>
</html>

2.promise发送ajax请求并获取到返回值

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<title>promise-ajax</title>
</head>
<body>
<script type="text/javascript">function foo(url) {return new Promise((resolve, reject) => {$.ajax({url,success(data){resolve(data);},error(err){reject(err);}});});}const url = 'http://localhost:30000/test/say';
p = foo(url)
p.then(result => console.log(result)) // "hello world!"</script></body>
</html>

3.在promise中使用fetch发送请求并获取返回结果

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<title>promise-ajax</title>
</head>
<body>
<script type="text/javascript">function foo(url) {return new Promise((resolve, reject) => {fetch(url).then(response => response.text()).then(data => {debugger;if (data.code === 404) {reject('请求异常:' + data.msg);} else {resolve(data);}}).catch(err => {reject('请求异常:' + err);});});}const url = 'http://localhost:30000/test/say';
p = foo(url)
p.then(result => console.log(result)) // "hello world!"
</script></body>
</html>

注意接口返回字符串类型要使用response.text(),我刚开始写的时候没有注意导致获取不到正确的结果

http://www.hskmm.com/?act=detail&tid=11994

相关文章:

  • iOS App 内存泄漏与性能调优实战 如何排查内存难题、优化CPU与GPU性能、降低耗电并提升流畅度(uni-app iOS制作优化指南)
  • 图解18:测试功能阶段
  • 图解19:Redis常见的14个场景
  • DDD - 技术落地
  • 一些dp技巧
  • 2025.09.20|第十一届全国地图学与地理信息系统学术大会在线报告_刘纪平报告
  • C++经典排序技巧总结
  • 静态资源管理:Nginx在Docker中的部署
  • C#文件操作入门
  • javascript基础 - Ref
  • ES——(一)基本概念 - 指南
  • python2.7+pandas
  • SAP集成HTTP接口(x-www-form-urlencoded格式)
  • iText与OpenPDF使用差异及中文处理完全指南 - 实践
  • 图解17:5中网络IO模型
  • Fmt库在CentOS 7的应用指南
  • 在k8s集群中解决master节点与node通信
  • 在Go中构建应用级IP防火墙机制
  • 用 R 语言实现验证码识别
  • 用 Lua 实现验证码识别
  • PHP中常见数组操作函数
  • AI翻唱神器,一键用你喜欢的歌手翻唱他人的曲目(附下载链接)
  • 修复Ubuntu系统文件损坏:手动fsck指令
  • Python网络请求库requests使用详述
  • Composer在PHP项目中的手动类自动加载策略
  • window表现驱动开发—视频呈现网络简介
  • 一类特征方程在数列递推中的应用
  • rust跨文件调用代码
  • 详细介绍:导师推荐毕设:基于SpringBoot+Vue的中小企业进销存管理系统设计
  • NIO重构UDP收发模块