zoukankan      html  css  js  c++  java
  • promise

    // 需求:封装一个方法,给一个读取文件的路径,方法能给我们返回文件内容

    const fs = require('fs')
    const path = require('path')
    
    // callback回调:第一个参数错误结果,第二个参数读取的文件内容
    function getFileByPath(fpath, callback) {
        fs.readFile(fpath, 'utf-8', (err, dataStr) => {
            if (err) return callback(err)
            callback(null, dataStr)
        })
    }
    
    getFileByPath(path.join(__dirname, './package.json'), (err, dataStr) => {
        if (err) return console.log(err.message)
        //console.log(dataStr)
        console.log(JSON.parse(dataStr).name)
    })
    function test(resolve, reject) {
        var timeOut = Math.random() * 2;
        console.log('set timeout to: ' + timeOut + ' seconds.');
        setTimeout(function () {
            if (timeOut < 1) {
                console.log('call resolve()...');
                resolve('200 OK');
            }
            else {
                console.log('call reject()...');
                reject('timeout in ' + timeOut + ' seconds.');
            }
        }, timeOut * 1000);
    }
    
    // var p1 = new Promise(test);
    // var p2 = p1.then(function (result) {
    //     console.log('成功:' + result);
    // });
    // var p3 = p2.catch(function (reason) {
    //     console.log('失败:' + reason);
    // });
    
    new Promise(test).then(res => console.log("succ")).catch(err => console.log("failed"))



  • 相关阅读:
    CVS,GIT,Mercurial和SVN比较
    ubuntu-使用终端配置网络
    编写简单的hashCode方法
    编写高质量equals方法
    文件上传和下载
    Java常用命令
    增删查改-MySQL
    Newton迭代法-C++
    二分法-C++
    适配器模式
  • 原文地址:https://www.cnblogs.com/xy-ouyang/p/11620390.html
Copyright © 2011-2022 走看看