当前位置:网站首页>Typescrip异步函数Promise使用
Typescrip异步函数Promise使用
2022-07-26 19:27:00 【RemoteDev】
var p = new Promise(function (resolve, reject) {
var x = 1;
if (x > 0) {
resolve({ msg: '异步调用成功', data: { x: 1, y: 2 } });
}
else {
reject({ msg: '异步调用失败', data: {} });
}
});
//异步调用结果
p.then(function (data) {
console.log('OK');
console.log(data);
//console.log(data.msg,data.data);
})["catch"](function (err) {
console.log(err);
});
//异步函数
function promiseFunc(t) {
console.log("".concat(t / 1000, "\u79D2\u540E\u8C03\u7528\u5F02\u6B65"));
return new Promise(function (resolve, reject) {
setTimeout(resolve, t, '异步调用完成');
});
}
//调用异步函数
promiseFunc(1000).then(function (value) { console.log(value); });
var promiseAction = new Promise(function (resolve, reject) {
console.log('执行了一些异步操作...');
resolve('异步操作完成了!');
});
promiseAction.then(function (value) { console.log(value); });
// @ts-ignore
// const XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest;
// let getDataAsync=(url)=>{
// let p = new Promise((resolve, reject) => {
// let c =new XMLHttpRequest();
// c.open('GET',url);
// c.onreadystatechange = h;
// c.responseType = 'json';
// c.setRequestHeader('Accept','application/json');
// c.send();
// function h(){
// if(this.readyState!==4){return;}
// if (this.status===200){
// console.log('请求成功返回:',this.status);
// resolve(this.response);
// }else {
// reject(new Error(this.statusText));
// }
// }
// });
// return p;
// };
// getDataAsync('http://192.168.31.180/data.json')
// .then(data=>{console.log(data);})
// .catch(err=>{console.log(err);});
//通过https加载json数据
var url = 'https://img-home.csdnimg.cn/data_json/toolbar/toolbar1105.json';
var url1 = 'https://mp-api.iqiyi.com/base/api/1.0/get_role';
var GetJsonData = function (url) {
var https = require('https');
https.get(url, function (response) {
var data = '';
//数据正在接收中...
response.on('data', function (chunk) {
data += chunk;
});
//数据接收完成
response.on('end', function () {
console.log('同步请求数据完成:', JSON.parse(data));
});
}).on("error", function (error) {
console.log("Error: " + error.message);
});
};
GetJsonData(url);
//异步请求JSON数据实现
var GetJsonDataAsync = function (url) {
var https = require('https');
return new Promise(function (resolve, reject) {
https.get(url, function (response) {
var data = '';
//数据正在接收中...
response.on('data', function (chunk) {
data += chunk;
});
//数据接收完成
response.on('end', function () {
//console.log(JSON.parse(data));
resolve(data); //数据接收完成
});
}).on("error", function (error) {
console.log("Error: " + error.message);
reject(new Error(error.message));
});
});
};
//异步调用
GetJsonDataAsync(url).then(function (value) {
console.log("======================下面为异步加载数据=================================");
if (typeof value === "string") {
console.log('异步加载请求数据完成:', JSON.parse(value));
}
})["catch"](function (err) { console.log(err); });
//通过request库请求json数据,使用前 sudo npm i -g request安装包
var request = require('request');
request(url, function (error, response, body) {
console.error('错误:', error);
console.log('状态码:', response && response.statusCode);
console.log('数据:', JSON.parse(body));
});
//异步方式
var RequestJsonAsync = function (url) {
return new Promise(function (resolve, reject) {
request(url, function (e, r, d) {
if (null != e) {
reject(new Error(e));
}
else {
resolve(JSON.parse(d));
}
});
});
};
RequestJsonAsync(url).then(function (value) {
console.log("==============request异步加载json===============================");
console.log(value);
})["catch"](function (err) { console.log(err); });
//nodejs needle库使用 ,使用前 npm i needle --save 安装包
var needle = require('needle');
needle.get(url, function (error, response) {
if (!error && response.statusCode == 200)
console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>", response.body);
});
//异步模式
needle('get', url, { json: true }).then(function (resp) {
if (resp.statusCode == 200) {
console.log(">>>>>>>>>>>>>>异步模式>>>>>>>>>>>>>>>>>>>>>>>>>>>>>", resp.body);
}
})["catch"](function (err) { console.log(err); });
//使用axios库使用,axios直接异步 使用前安装 npm i -g axios --save
var axios = require('axios');
axios.get(url)
.then(function (res) {
console.log(res);
})["catch"](function (err) {
console.log(err);
});
//axios支持多请求并发
axios.all([
axios.get(url),
axios.get(url1)
]).then(axios.spread(function (res1, res2) {
console.log(res1);
console.log(res2);
}))["catch"](function (err) {
console.log(err);
});
//supertaget库使用
var superagent = require('superagent');
superagent.get(url)
.end(function (err, res) {
if (err) {
return console.log(err);
}
console.log("superagent库调用==========>", res.body);
});
//fetch库使用 使用前安装 npm i node-fetch 3x版本只能import导入 --save 支持异步
// @ts-ignore
// import fetch from 'node-fetch'; //不能在模块之外使用
// fetch(url)
// .then(res => res.json()) // expecting a json response
// .then(json => {
// console.log(json);
// })
// .catch(err => {
// console.log(err);
// });
var p1 = new Promise(function (resolve, reject) {
resolve('p1 resolve');
});
var p2 = new Promise(function (resolve, reject) {
resolve('p2 resolve');
});
//只要p1,p2中的其中一个有状态改变,马上返回pRace
var pRace = Promise.race([p1, p2]);//将多个Promise生成一个Promise
pRace.then(function (value) {
console.log(value);
});
边栏推荐
- 猎聘问卷星,成为微信「寄生虫」
- 2022年下半年(软考高级)信息系统项目管理师报名条件
- 一年卖7亿,德州扒鸡赶考IPO
- C#异步编程看这篇就够了
- Dio problem summary
- Kingbases SQL language reference manual of Jincang database (15. SQL statement: create materialized view to create schema)
- three. Two methods of making Earth annotation with JS
- Silent desktop fan chip dltap703sd Jericho
- Kingbases SQL language reference manual of Jincang database (13. SQL statement: alter synonym to comment)
- 本机号码一键登录原理与应用(荣耀典藏版)
猜你喜欢
随机推荐
【二叉树】将二叉搜索树变平衡
EFCore Migrations的深入研究
静音台式风扇芯片-DLTAP703SD-杰力科创
numpy.put()
SQL注入
cv2.resize()
Is flush reliable? I just started to learn financial management. Is it safe to open a securities account?
开源闹出乌龙事件,可能你不知道这五种开源协议
有点酷,使用 .NET MAUI 探索太空
SQL injection
Zabbix调用api检索方法
一文读懂 .NET 中的高性能队列 Channel
开源 | AREX-携程无代码侵入的流量回放实践
金仓数据库 KingbaseES SQL 语言参考手册 (15. SQL语句:CREATE MATERIALIZED VIEW 到 CREATE SCHEMA)
Use request header authentication to test API interfaces that need authorization
three.js 制作地球标注的两种方法
N圆最密堆积、最小外接正方形的matlab求解(二维、三维等圆Packing 问题)
Fasttunnel open source intranet penetration framework
Strengthen supervision on secret room escape and script killing, and focus on strengthening fire safety and juvenile protection
.net GC workflow






![[Android] the black technology behind kotlin's rapid compilation. Learn about it~](/img/d6/ae107f75c158e97913e6d75eac5b84.png)


