当前位置:网站首页>Typescript asynchronous function promise use
Typescript asynchronous function promise use
2022-07-26 20:20:00 【RemoteDev】
var p = new Promise(function (resolve, reject) {
var x = 1;
if (x > 0) {
resolve({ msg: ' Asynchronous call succeeded ', data: { x: 1, y: 2 } });
}
else {
reject({ msg: ' Asynchronous call failed ', data: {} });
}
});
// Asynchronous call result
p.then(function (data) {
console.log('OK');
console.log(data);
//console.log(data.msg,data.data);
})["catch"](function (err) {
console.log(err);
});
// An asynchronous function
function promiseFunc(t) {
console.log("".concat(t / 1000, "\u79D2\u540E\u8C03\u7528\u5F02\u6B65"));
return new Promise(function (resolve, reject) {
setTimeout(resolve, t, ' Asynchronous call complete ');
});
}
// Calling an asynchronous function
promiseFunc(1000).then(function (value) { console.log(value); });
var promiseAction = new Promise(function (resolve, reject) {
console.log(' Performed some asynchronous operations ...');
resolve(' The asynchronous operation is complete !');
});
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(' Request returned successfully :',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);});
// adopt https load json data
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 = '';
// Data is being received ...
response.on('data', function (chunk) {
data += chunk;
});
// Data reception complete
response.on('end', function () {
console.log(' Synchronization request data completed :', JSON.parse(data));
});
}).on("error", function (error) {
console.log("Error: " + error.message);
});
};
GetJsonData(url);
// Asynchronous requests JSON Data implementation
var GetJsonDataAsync = function (url) {
var https = require('https');
return new Promise(function (resolve, reject) {
https.get(url, function (response) {
var data = '';
// Data is being received ...
response.on('data', function (chunk) {
data += chunk;
});
// Data reception complete
response.on('end', function () {
//console.log(JSON.parse(data));
resolve(data); // Data reception complete
});
}).on("error", function (error) {
console.log("Error: " + error.message);
reject(new Error(error.message));
});
});
};
// Asynchronous call
GetJsonDataAsync(url).then(function (value) {
console.log("====================== The following is asynchronous loading data =================================");
if (typeof value === "string") {
console.log(' Asynchronous load request data complete :', JSON.parse(value));
}
})["catch"](function (err) { console.log(err); });
// adopt request Library request json data , Before using sudo npm i -g request Installation package
var request = require('request');
request(url, function (error, response, body) {
console.error(' error :', error);
console.log(' Status code :', response && response.statusCode);
console.log(' data :', JSON.parse(body));
});
// Asynchronous way
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 Load asynchronously json===============================");
console.log(value);
})["catch"](function (err) { console.log(err); });
//nodejs needle Library usage , Before using npm i needle --save Installation package
var needle = require('needle');
needle.get(url, function (error, response) {
if (!error && response.statusCode == 200)
console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>", response.body);
});
// Asynchronous mode
needle('get', url, { json: true }).then(function (resp) {
if (resp.statusCode == 200) {
console.log(">>>>>>>>>>>>>> Asynchronous mode >>>>>>>>>>>>>>>>>>>>>>>>>>>>>", resp.body);
}
})["catch"](function (err) { console.log(err); });
// Use axios Library usage ,axios Direct asynchronous Install before use 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 Support multi request concurrency
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 Library usage
var superagent = require('superagent');
superagent.get(url)
.end(function (err, res) {
if (err) {
return console.log(err);
}
console.log("superagent Library call ==========>", res.body);
});
//fetch Library usage Install before use npm i node-fetch 3x Version can only import Import --save Asynchronous Support
// @ts-ignore
// import fetch from 'node-fetch'; // Cannot be used outside the module
// 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');
});
// as long as p1,p2 One of them has a state change , Go back to pRace
var pRace = Promise.race([p1, p2]);// Will be multiple Promise Generate a Promise
pRace.then(function (value) {
console.log(value);
});
边栏推荐
- 打字比赛圆满结束!
- 20220725 tree array introspection
- Intranet penetration learning (II) information collection
- 密室逃脱、剧本杀加强监管 重点加强消防安全和未成年人保护
- 解决AttributeError: module ‘win32com.gen_py.00020813-0000-0000-C000-000000000046x0x1x9‘ has no attribu
- 一文读懂 Kubernetes的四种服务类型!
- 直播预约有奖| 高级咨询顾问徐雁斐:效能度量如何助力高效精细的外包管理
- Array operations add, delete, modify, and query
- EtherCAT synchronization mode
- Meeting seating & submission of meeting OA
猜你喜欢
随机推荐
ES6的方法&类数组转成真正的数组&判断数组的方法
DevSecOps,让速度和安全兼顾
Vite 配置 Eslint 规范代码
App Uploader下载安装
SQL injection
20220725树状数组入门反思
Dio问题总结
[Android] the black technology behind kotlin's rapid compilation. Learn about it~
A little cool, explore space with.Net Maui
EtherCAT 同步模式
会议OA之会议排座&送审
医疗直播平台需要什么功能
I hope some suggestions on SQL optimization can help you who are tortured by SQL like me
Week 6 Convolutional Neural Networks (CNNs)
UE5编辑器Slate快速入门【开篇】
事务回滚,同时记录异常信息
阿里三面:MQ 消息丢失、重复、积压问题,如何解决?
How to build a super interface collaboration platform: count the six weapons of apifox
T246836 [LSOT-1] 暴龙的土豆
Cookie和Session









