当前位置:网站首页>[JS encapsulates a simple asynchronous API to obtain asynchronous operation results and process parsing]
[JS encapsulates a simple asynchronous API to obtain asynchronous operation results and process parsing]
2022-07-18 21:00:00 【Brave * Niuniu】
js Encapsulate a simple asynchronous API, Get the result of asynchronous operation
Usually when encapsulating a synchronous function , We just need to be in the function return The result is OK .
like this :
function fn () {
var data = 'hello';
return data;
}
var data = fn();
console.log(data) // Output : hello
js Asynchronous operations in :
* Timer
* Event binding
* ajax Asynchronous mode
* Callback function
How to get the result of asynchronous operation in a function , For example, call a function fn() Get internal variables data Value :
(1)
function fn() {
setTimeout(function () {
var data = 'Hi'
},1000)
console.log(data)
}
fn()
Because of the timer 1 Seconds later , But the code has already been executed console, So the output is data is not defined
(2)
function fn() {
setTimeout(function () {
var data = 'Hi'
return data
},1000)
}
console.log(fn())
fn Function has no return value , So the output is undefined
return It's the one in the timer function Conduct return Of , And fn irrelevant
(3)
var data = '^_^'
function fn() {
setTimeout(function () {
data = 'Hi'
},1000)
return data
}
console.log(fn())
The timer is asynchronous , So the code doesn't wait , Will be executed directly to return, Assignment operation is not performed , So the result is _
The right way
If you need to get the result of an asynchronous operation in a function , It must be obtained through the callback function
function fn(callback) {
// Pass in a function , It is equivalent to creating a new one called callback Function of
//var callback = function (data) { console.log(data) }
setTimeout(function () {
var data = 'Hi'
callback(data)
},1000)
}
fn(function (data) {
console.log(data)
})

The key step is to call callback , The reason why the data cannot be obtained in the previous situation is because ,data Variables are defined in the timer , Function unequal timer function The execution immediately wants to get the data , That is, you come to pick up the goods before others' products are ready , This shows that you can't
Now? callback At the end of the timer function Internal execution , And in data Execute after variable initialization , You can guarantee to get the data , Even if the timer is 10 Seconds or even a minute doesn't matter , Wait anyway data Execute after initialization callback
in other words , When it is really implemented setTimeout The function inside , If called callback function , Then you can call to execute fn Callback function for callback, So as to achieve the purpose of transmitting asynchronous results
There is another way to get data Value , Is to define it as a global variable , The timer will execute in one second , Then call it in two seconds , But this way is not interesting
var data
function fn() {
setTimeout(function () {
data = 'Hi'
},1000)
}
fn()
setTimeout(function () {
console.log(data) // Two seconds later, the result is Hi, If the 2000 Change it to 0, The result is undefined
},2000)
console.log('______start__________');
var data = '^_^'
function fn(callback){
setTimeout(() => {
var data = 1+2
callback(data)
},1000);
}
function callback(data){
// Get the asynchronous array and operate here
console.log(data);
}
fn(callback)
console.log('______end__________');
console.log(' end ');
边栏推荐
猜你喜欢

What skills do software test engineers need to master if they need to speak 20K? I dare to be higher with these skills~

第十三篇,STM32 I2C串行总线通信实现

Pytorch 深度可分离卷积和MobileNet_v1

Find out the motivation and needs of enterprise location, and carry out investment attraction work efficiently

The concept and properties of | double integral under high numbers | high numbers | handwritten notes

I2C通信协议实现在OLED显示屏数据显示

剑指 Offer 53 - II. 0~n-1中缺失的数字

Tableau JDBC connection graphdb

Electron安装配置

初探BLE 蓝牙电池服务
随机推荐
R语言ggplot2可视化:使用ggpubr包的gghistogram函数可视化直方图、使用add参数在直方图中添加均值虚线竖线、横轴添加轴须图(rug plot)
Little sister, I'm coming
putchar()
Sword finger offer 57 And are two numbers of S
EPIC-KBS9工控机刷机文档
R语言ggplot2可视化:使用ggpubr包的ggecdf函数可视化经验累积密度分布函数曲线(Empirical cumulative density function)
R语言ggplot2可视化:使用ggpubr包的ggballoonplot函数可视化分面气球图(可视化由两个分类变量组成的列联表)、facet.by参数指定分面变量
程序员都看不懂的代码 渐隐渐现1920-500(1)
What is industrial planning? How to make industrial planning for industrial parks
[动态规划]DP21 正则表达式匹配-较难
[try to hack] NTLM and LM Foundation
apache日志相关
Code that programmers can't understand
博客从 CloudBase 迁移至云主机
Redis-Cluster集群、
高级程序员面试常用问题,你知道回答吗? 带答案
VirtualBox虚拟机无法启动,E_FAIL( 0x80004005)
Three ways for industrial parks to enhance the service capacity of enterprises
scrcpy投屏
GD32F4(6):晶振引发串口乱码