疑问:感觉会报错,因为执行到defer.promise.then这时候还没到defer.resolve,因为异步读文件,总归会慢
解答:先执行defer.promise.then,是给callback赋值,函数的赋值会比较抽象,callback得到函数的赋值后,是函数就该等待执行,等待resolve的时候,执行,其实也是回调的方式,
关键点:实参是函数,就是形参被复值成函数,把形参当函数看
var Defer = function(){ var value,callback; return { resolve :function(val){ value = val; callback(val); }, promise:{ then:function(fn){ callback = fn; } } } } var fs = require(‘fs‘); var defer = new Defer(); fs.readFile(‘data/account/accountInfo_0.html‘,(err,data)=>{ console.log(2) defer.resolve(data) }) console.log(1) defer.promise.then(function(resData){ console.log(3) console.log(resData) });
时间: 2024-10-19 10:17:42