当前位置:网站首页>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);
});
边栏推荐
- Kingbasees SQL language reference manual of Jincang database (17. SQL statement: discard to drop language)
- three. JS tag and pop-up the earth
- three.js 制作地球标注的两种方法
- .net GC workflow
- Jincang database kingbasees SQL language reference manual (18. SQL statement: drop materialized view to drop synonym)
- 【JVM 系列】JVM 调优
- 操作系统常见面试题目总结,含答案
- Student‘s t分布
- 计算机专业面试题目总结,总导航
- EtherCAT 同步模式
猜你喜欢

Codeforces Round #810 (Div. 2)(A~C)

20220725 tree array introspection

How to build a super interface collaboration platform: count the six weapons of apifox

Vs how to read data in MySQL (by the way, the problem of Chinese garbled code is solved through code)

银行业概览

Record an analysis of a.Net property management background service stuck

任务二 kaggle糖尿病检测

计算机组成原理常见面试题目总结,含答案

C# 使用默认转型方法

内网渗透学习(二)信息收集
随机推荐
正则表达式
numpy.newaxis
three.js 给地球加标签和弹窗
Is flush reliable? I just started to learn financial management. Is it safe to open a securities account?
7岁男童因下棋太快?机器人竟夹断其手指
svn使用碎碎念
潘多尼亚精灵 VoxEdit 创作大赛
Jincang database kingbasees SQL language reference manual (18. SQL statement: drop materialized view to drop synonym)
Kingbasees SQL language reference manual of Jincang database (12. SQL statement: alter language to alter subscription)
【JVM 系列】JVM 调优
Strengthen supervision on secret room escape and script killing, and focus on strengthening fire safety and juvenile protection
this指向-超经典面试题
2022年下半年(软考高级)信息系统项目管理师报名条件
.NET GC工作流程
three. Two methods of making Earth annotation with JS
Introduction to component functions of blueprism process business object Chapter 3 of RPA
STM32F103 active buzzer driver
20220725树状数组入门反思
.net GC workflow
DevSecOps,让速度和安全兼顾