异步变同步

news/2024/7/10 23:52:14 标签: es6
  1. promise.all
let behind = (time) => {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            console.log( `${time}毫秒后` )
            resolve( `${time}毫秒后` )
        }, time)
    })
}

let p2 = behind(3000);
let p1 = behind(2000);
//两个以上ajax数据回来前显示loading
Promise.all([p2, p1]).then(res => {
    console.log('tag', res)
    // 2000毫秒后
    // 3000毫秒后
    // tag [ '3000毫秒后', '2000毫秒后' ]
}).catch(error => {
    console.log('tag', error)
})
  1. async await
function func1() {
    return new Promise(resolve => {
        setTimeout(() => {
            resolve("func1 success")
        }, 1000)
    })
}

function func2() {
    return new Promise(resolve => {
        setTimeout(() => {
            resolve("func2 success")
        }, 2000)
    })
}

let funcTest = async function() {
    try {
        let p2 = await func2();
        console.log(p2)
        let p1 = await func1();
        console.log(p1)
        //first. func2 success 
        //second func1 success
    } catch (error) {
        console.log(error)
    }

}
funcTest();

http://www.niftyadmin.cn/n/1769524.html

相关文章

【c语言】 与倒数第二个字符相同的的个数

前言 有同学问了我这样一个问题,思路是:首先建立一个数组int array[100]存储字符,再用gets函数输入,统计gets函数存储的字符串的实际长度,ta的做法是int lengthsizeof(array)/sizeof&#xff…

【c++】输出学生姓名以及成绩的表格

前言 第一次写c&#xff0c;不知道可不可以这样写呢&#xff0c;不过可以运行就可以了 有个同学问我&#xff0c;那总要稍微研究一下&#xff0c;最后研究的结果就是&#xff0c;还是用类似于c语言的方法解决问题吧 代码实测 #include <iostream> using namespace s…

数组简单递归

数组简单递归 var data1 [{"uid_step": "1","step_to": [{"uid_step": "2","step_to": [{"uid_step": "6","step_to": null}]},{"uid_step": "3","ste…

【探究】MatLab对于方程的求解

问题提出&#xff08;答案在最后以图片形式呈现&#xff09; 对于任意的一元方程&#xff0c;如何求解&#xff0c;在日常生活中,通常使用计算器的solve键直接求解&#xff0c;但是实际情况是当你用拿在手上的计算器去计算如下的方程时&#xff1a; 1/x1/(x0.05)1/(x0.1)1/(x…

函数加new与不加new区别

没有设置返回值 function fruit(type) {this.type type;console.log("this", this); } let fruit1 new fruit("apple"); // fruit {type: "apple"} let fruit2 fruit("apple"); //windowconsole.log(fruit1, fruit1) //fruit {typ…

【每日一坑】Java 父类与子类(1)

下列程序执行的结果应该是 &#xff08; &#xff09; a.Son Son B b.Base Son B c. 编译错误 class Base{public void method() {System.out.println("Base");} } class Son extends Base{public void method() {System.out.println("son");}public stat…

js原生自定义事件

html <button id"btn">按钮</button> <div id"m"></div> <div id"n"></div>Event 无参数传递 let btn document.getElementById("btn");let m document.getElementById("m");let n …