zoukankan      html  css  js  c++  java
  • Promise简单使用,需要在ES6以上

     //Promise延时顺序执行

    var waitOne = new Promise(function(resolve, reject) {
         setTimeout(function(){ resolve(1)}, 1000);
    }); 
    var waitSecond = new Promise(function(resolve, reject) {
         setTimeout(function(){ resolve(1)}, 1000);
    }); 
    waitOne.then(function() {
        console.log("Hello"); // 1秒后输出"Hello"
        return new Promise(function(resolve, reject) {
         setTimeout(function(){ resolve(1)}, 1000);
        });
    }).then(function() {
        console.log("Hi"); // 2秒后输出"Hi"
    });
    new Promise(function(resolve , reject) {
        resolve(1);
    }).then(function(val) {
        console.log(val);
        return new Promise(function(resolve , reject) {
            resolve(2);
        });
    }).then(function(val) {
        console.log(val);
        return new Promise(function(resolve , reject) {
            resolve(3);
        });
    }).then(function(val) {
        console.log(val);
        return new Promise(function(resolve , reject) {
            resolve(4);
        });
    }).then(function(val) {
        console.log(val);
    });
    
    //输出:
    //      1
    //      2
    //      3
    //      4
    下面代码中,setTimeout(fn, 0)在下一轮“事件循环”开始时执行,Promise.resolve()在本轮“事件循环”结束时执行,console.log('one')则是立即执行,因此最先输出。 
    setTimeout(function () {
      console.log('three');
    }, 0);
    
    Promise.resolve().then(function () {
      console.log('two');
    });
    
    console.log('one');
  • 相关阅读:
    迭代器和生成器
    装饰器进阶
    闭包和装饰器
    函数的嵌套
    函数的参数
    什么是粘包现象
    模拟ssh远程命令执行
    客户端与服务端代码bug修复和加入循环
    用socket实现简单的套接字通讯
    网络编程之客户端和服务端,
  • 原文地址:https://www.cnblogs.com/shurun/p/11936068.html
Copyright © 2011-2022 走看看