我编写的代码看起来像:
function getStuffDone(param) { | function getStuffDone(param) {
var d = Q.defer(); /* or $q.defer */ | return new Promise(function(resolve, reject) {
// or = new $.Deferred() etc. | // using a promise constructor
myPromiseFn(param+1) | myPromiseFn(param+1)
.then(function(val) { /* or .done */ | .then(function(val) {
d.resolve(val); | resolve(val);
}).catch(function(err) { /* .fail */ | }).catch(function(err) {
d.reject(err); | reject(err);
}); | });
return d.promise; /* or promise() */ | });
} | }
Run Code Online (Sandbox Code Playgroud)
有人告诉我这个被称为" 延迟反模式 "或" Promise构造函数反模式 ",这个代码有什么不好,为什么这被称为 …
我已经开发了几年的JavaScript,我根本不理解有关承诺的大惊小怪.
似乎我所做的只是改变:
api(function(result){
api2(function(result2){
api3(function(result3){
// do work
});
});
});
Run Code Online (Sandbox Code Playgroud)
无论如何,我可以使用像async这样的库,例如:
api().then(function(result){
api2().then(function(result2){
api3().then(function(result3){
// do work
});
});
});
Run Code Online (Sandbox Code Playgroud)
哪个代码更多,可读性更低.我没有在这里获得任何东西,它也不会突然神奇地"平坦".更不用说必须将事物转换为承诺.
那么,这里的承诺有什么大惊小怪?
有什么区别:
new Promise(function(res, rej) {
res("aaa");
})
.then(function(result) {
return "bbb";
})
.then(function(result) {
console.log(result);
});Run Code Online (Sandbox Code Playgroud)
还有这个:
new Promise(function(res, rej) {
res("aaa");
})
.then(function(result) {
return Promise.resolve("bbb");
})
.then(function(result) {
console.log(result);
});Run Code Online (Sandbox Code Playgroud)
我问我使用Angular和$ http服务与链接.then()有不同的行为.有点太多的代码因此首先是上面的例子.
无论是ES6 Promise还是蓝鸟Promise,Q Promise等.
如何测试以查看给定对象是否为Promise?
请考虑以下以串行/顺序方式读取文件数组的代码.readFiles返回一个promise,只有在按顺序读取所有文件后才会解析.
var readFile = function(file) {
... // Returns a promise.
};
var readFiles = function(files) {
return new Promise((resolve, reject) =>
var readSequential = function(index) {
if (index >= files.length) {
resolve();
} else {
readFile(files[index]).then(function() {
readSequential(index + 1);
}).catch(reject);
}
};
readSequential(0); // Start!
});
};
Run Code Online (Sandbox Code Playgroud)
上面的代码可以工作,但我不喜欢按顺序进行递归递归.是否有一种更简单的方法可以重写此代码,以便我不必使用我的奇怪readSequential功能?
最初我试图使用Promise.all,但这导致所有readFile调用同时发生,这不是我想要的:
var readFiles = function(files) {
return Promise.all(files.map(function(file) {
return readFile(file);
}));
};
Run Code Online (Sandbox Code Playgroud) 在Node.js添加了对promises的原生支持之后,还有理由使用像Q或BlueBird这样的库吗?
例如,如果您正在开始一个新项目并让我们在这个项目中假设您没有任何使用这些库的依赖项,那么我们是否可以说实际上没有理由使用这些库?
我在angularjs中实现了$ q.all,但我无法使代码工作.这是我的代码:
UploadService.uploadQuestion = function(questions){
var promises = [];
for(var i = 0 ; i < questions.length ; i++){
var deffered = $q.defer();
var question = questions[i];
$http({
url : 'upload/question',
method: 'POST',
data : question
}).
success(function(data){
deffered.resolve(data);
}).
error(function(error){
deffered.reject();
});
promises.push(deffered.promise);
}
return $q.all(promises);
}
Run Code Online (Sandbox Code Playgroud)
这是我的控制器调用服务:
uploadService.uploadQuestion(questions).then(function(datas){
//the datas can not be retrieved although the server has responded
},
function(errors){
//errors can not be retrieved also
})
Run Code Online (Sandbox Code Playgroud)
我认为在我的服务中设置$ q.all存在一些问题.
有人可以解释一下$q.whenAngularJS的工作原理吗?我正在尝试分析$http工作方式,并发现了这个:
var promise = $q.when(config);
Run Code Online (Sandbox Code Playgroud)
这是来自Chrome控制台的配置对象:
Object {transformRequest: Array[1], transformResponse: Array[1], cache: Object, method: "GET", url: "/schedule/month_index.html"…}
cache: Object
headers: Object
method: "GET"
transformRequest: Array[1]
transformResponse: Array[1]
url: "/schedule/month_index.html"
__proto__: Object
Run Code Online (Sandbox Code Playgroud)
接下来发生什么?该对象如何被解决或拒绝?
我有一个简单的节点模块,它连接到一个数据库,并有几个接收数据的函数,例如这个函数:
dbConnection.js:
import mysql from 'mysql';
const connection = mysql.createConnection({
host: 'localhost',
user: 'user',
password: 'password',
database: 'db'
});
export default {
getUsers(callback) {
connection.connect(() => {
connection.query('SELECT * FROM Users', (err, result) => {
if (!err){
callback(result);
}
});
});
}
};
Run Code Online (Sandbox Code Playgroud)
该模块将从不同的节点模块以这种方式调用:
app.js:
import dbCon from './dbConnection.js';
dbCon.getUsers(console.log);
Run Code Online (Sandbox Code Playgroud)
我想使用promises而不是回调来返回数据.到目前为止,我已经阅读了以下线程中的嵌套promise:使用嵌套Promise编写清洁代码,但我找不到任何对这个用例来说足够简单的解决方案.result使用承诺返回的正确方法是什么?
我有一个javascript类,每个方法都返回一个Qpromise.我想知道为什么this未定义method2和method3.有没有更正确的方法来编写此代码?
function MyClass(opts){
this.options = opts;
return this.method1()
.then(this.method2)
.then(this.method3);
}
MyClass.prototype.method1 = function(){
// ...q stuff...
console.log(this.options); // logs "opts" object
return deferred.promise;
};
MyClass.prototype.method2 = function(method1resolve){
// ...q stuff...
console.log(this); // logs undefined
return deferred.promise;
};
MyClass.prototype.method3 = function(method2resolve){
// ...q stuff...
console.log(this); // logs undefined
return deferred.promise;
};
Run Code Online (Sandbox Code Playgroud)
我可以通过使用bind:
function MyClass(opts){
this.options = opts;
return this.method1()
.then(this.method2.bind(this))
.then(this.method3.bind(this));
}
Run Code Online (Sandbox Code Playgroud)
但不完全确定为什么bind有必要; 正在.then()杀戮this?
q ×10
promise ×9
javascript ×8
bluebird ×5
angularjs ×3
node.js ×3
es6-promise ×2
callback ×1
deferred ×1
sequential ×1
this ×1