promise es6,es7

promise es7写法

let sleep = (timeountMS) => new Promise((resolve) => {
    setTimeout(resolve, timeountMS,"lja");//第三个参数:计时器到期后,将传递给func指定的函数的其他参数
});
(async()=>{for(var i=0;i<5;i++){
let result = await sleep(1000);
console.log(new Date, i,result);
}
})()

promise.all es6

const tasks = []; // 这里存放异步操作的 Promise
const output = (i) => new Promise((resolve) => {
    setTimeout(() => {
        console.log(new Date, i);
        resolve();
    }, 1000 * i);
});
 
// 生成全部的异步操作
for (var i = 0; i < 5; i++) {
    tasks.push(output(i));
}
 
// 异步操作完成之后,输出最后的 i
Promise.all(tasks).then(() => {
    setTimeout(() => {
        console.log(new Date, i);
    }, 1000);

参考网址:https://blog.csdn.net/sinat_17775997/article/details/74982484

当你打开参考网址的大佬的博客看到左侧的时候,你就知道是么叫做大佬。

es6 promise 

var sleep = function (time) {
    return new Promise(function (resolve, reject) {
    console.log(1)
        setTimeout(function () {
            resolve();
        }, time);
    console.log(13)
    })
};
 
var start = async function () {
    console.log('start');
    await sleep(3000);
    console.log('end');
};
 
start();            

结果是

start
 1
13
Promise {<pending>}
 end

为什么中间会那样排序?

https://zhuanlan.zhihu.com/p/23312442   知乎大佬的回答涉及到promise原理性知识和机制.

猜你喜欢

转载自www.cnblogs.com/lujunan/p/11624964.html