promises和AJAX调用都是异步操作.可以使用两者进行GET/POST请求.<< 编辑:那是一个错误的陈述
那么它们之间的区别是什么?何时最好使用一个而不是另一个?
还有一件事:
最近我遇到了一个承诺,它的身体有一个AJAX.为什么在异步操作中放置异步操作?这就像把面包放在面包三明治里.
function threadsGet() {
return new Promise((resolve, reject) => {
$.getJSON('api/threads')
.done(resolve)
.fail(reject);
})
}
Run Code Online (Sandbox Code Playgroud)
这里使用jQuery.AJAX调用具有Promise行为和属性.我没有早点得到,但这是我的想法:我们可以在承诺中做点什么.然后使用AJAX调用并在done
函数中传递已解析的Promise逻辑.特别是在这个例子中没有.
现在我看到我混淆了两个.它们有两个不同的东西.仅仅因为它们是异步的,并不意味着它们是可以互换的.
==============
编辑2:我发现有些材料很有用:
我正在尝试使用promises从Firebase填充一些数据.这是DB结构:
- domain name(or something)
|--highscore
|--Foo: 50
|--Bar: 60
Run Code Online (Sandbox Code Playgroud)
代码:
var arr=[];
highscoreRef.child('highscore').once('value').then(function(snapshot) {
snapshot.forEach(function(data) {
arr.push({playerName: data.key(), score: data.val()});
});
}, function(error) {
console.error(error);
});
Run Code Online (Sandbox Code Playgroud)
我明白了 Uncaught Error: Query.once failed: Was called with 1 argument. Expects at least 2.
这是否意味着我必须向Foo和Bar添加至少2个属性?防爆.Foo = {playerName:name,score:50}
当前的数据库安排符合我的需求.