博大精深的Promise

 

不定期收集一些和Promise相关的代码片段,各种缘由自行体会。

一、

function timeout(ms = 100) {


    /*1. 为何这种写法,立即返回数据而不是等到过了 ms 后才返回*/
     return new Promise((resolve, reject) => {
       setTimeout(resolve('World'), ms);
     });


    /*2. 为何这种写法,等到过了 ms 后才返回*/
    //return new Promise((resolve, reject) => {
    //    setTimeout(resolve, ms, 'World');
    //});
}


timeout(1000)
    .then(value => {
        console.log(`Hello, ${value}`);
    })
    .catch(err => {
        console.error(err);
    });


二、


setTimeout(function () {
    console.log(1)
}, 0);
new Promise(function executor(resolve) {
    console.log(2);
    for (var i = 0; i < 10000; i++) {
        i == 9999 && resolve();
    }
    console.log(3);
}).then(function () {
    console.log(4);
});
console.log(5);

 

三、这个是对<不确定函数数目使用nodeJS的async.parallel方法> 的补充,这种方案也可以实现目的

console.log('line 1')
const wait = function (time) {
    // 定义一个 promise 对象
    const promise = new Promise((resolve, reject) => {
        // 将之前的异步操作,包括到这个 new Promise 函数之内
        const task = function () {
            console.log('执行完成')
            resolve()  // callback 中去执行 resolve 或者 reject
        }
        setTimeout(task, time)
    })
    // 返回 promise 对象
    return promise
}
const w = wait
const readFileAsync = async function () {
    console.log('1')
    const f1 = await w(1000)
    console.log('2')
    const f2 = await w(100)
    console.log('3')
    const f3 = await w(10)
    console.log('4')
    const f4 = await w(1)
    console.log('5')
}
readFileAsync();

console.log('line 3')

四,

var myTimeout = function (time) {
    return new Promise(function(yes,no){
        setTimeout(() => {
            console.log('定时器到了:'+time);
            yes(time+1);
        }, time)
    });
}

myTimeout(1000)
.then(myTimeout)
.then(myTimeout)
.then(myTimeout)
.catch(function (error) {
    //用catch捕捉前面的错误
    console.log('sorry, 请求失败了, 这是失败信息:', error);
});

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值