zoukankan      html  css  js  c++  java
  • promise

    var fs = require('fs')
    
    //promise不是异步,但往往在里面封装 异步API
    var p = new Promise(function (res, rej) { fs.readFile('./00.txt','utf8', function (err, data) { if (err) { rej(err) } else { //pending 状态改变为 resolved res(data) } }) }) var p1 = new Promise(function (res, rej) { fs.readFile('./01.txt','utf8', function (err, data) { if (err) { rej(err) } else { res(data) } }) }) //当p 成功/失败了 然后(then) 做指定的操作,then方法接受的function 就是容器中的 res 函数 p .then(function (data) { console.log(data) return p1 //p1 中的res函数就是下一个then方法的第一个参数 }, function (err) { console.log('读取文件失败') }) .then(function (data) { console.log(data) }, function (err) { console.log('读取文件失败') })

    封装 promise

    var fs = require('fs')
    
    function pReadFile(path) {
        return new Promise(function (res, rej) {
            fs.readFile(path,'utf8', function (err, data) {
                if (err) {
                    rej(err)
                } else {
                    res(data)
                }
            })
        })
    }
    
    pReadFile('./00.txt')
        .then(function (data) {
            console.log(data)
            return pReadFile('./01.txt')
        }, function (err) {
            console.log('读取文件失败')
        })
        .then(function (data) {
            console.log(data)
        }, function (err) {
            console.log('读取文件失败')
        })
    var fs = require('fs')
    var p = new Promise(function (res, rej) {
        fs.readFile('./00.txt','utf8', function (err, data) {
            if (err) {
                rej(err)
            } else {
                //pending 状态改变为 resolved
                res(data)
            }
        })
    })
    var p1 = new Promise(function (res, rej) {
        fs.readFile('./01.txt','utf8', function (err, data) {
            if (err) {
                rej(err)
            } else {
                //pending 状态改变为 resolved
                res(data)
            }
        })
    })
    //当p 成功了 然后(then) 做指定的操作,then方法接受的function 就是容器中的 res 函数
    p
        .then(function (data) {
            console.log(data)
            return p1   //p1 中的res函数就是下一个then方法的第一个参数
        }, function (err) {
            console.log('读取文件失败')
        })
        .then(function (data) {
            console.log(data)
        }, function (err) {
            console.log('读取文件失败')
        })
  • 相关阅读:
    Web-js中级-11月13日
    Web-js中级-11月12日
    Web-js中级-11月9日
    Web-js中级-11月8日
    Web-js中级-11月7日
    django中自定义了manager函数,使用的时候报错AttributeError: 'Manager' object has no attribute 'title_count'
    django模型篇:一对一、一对多、多对多,添加,批量插入和查询操作
    from django.core.context_processors import crsf报错
    python报错:Exception Value:can only concatenate str (not "bytes") to str
    使用tkinter设计一个简单的加法计算器
  • 原文地址:https://www.cnblogs.com/huangyuanning/p/11858004.html
Copyright © 2011-2022 走看看