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(),我刚开始写的时候没有注意导致获取不到正确的结果