运行 多个 JavaScript Promise 和 RSVP.js Promise 库
Run multiple JavaScript Promises with RSVP.js Promise Library
下面的简单演示 JavaScript 代码使用 RSVP.js Promise 库 https://github.com/tildeio/rsvp.js/ 使用 AJAX 加载一些 JSON 数据,并在完成时触发一些加载所有 JSON 数据后的代码。
我想扩展它以在 JSON 数据加载后执行更多不是 AJAX 请求的承诺。
例如,在 JSON 数据加载后,我想创建另一个 Promise,它将 运行 一个函数,该函数将设置一些 DOM 事件 handlers/listeners。
在设置事件处理的功能之后,我想在事件设置完成后 运行 一些其他功能。
我是新手,仍在学习 Promises,在某些情况下仍在学习 JavaScript,因此我需要一些帮助。在下面和 JSFIddle 上扩展我的示例代码将非常感谢!
我相信如果显示如何向我的演示添加 1 个承诺,那么我在最终应用程序中添加所需的数量就足够了。
以下代码的 JSFIddle 演示:http://jsfiddle.net/jasondavis/fttzoggj/
var jsonPromiseCache = {};
// AJAX function to load JSON data using Promise()
var getJsonDataPromise = function(url, key) {
if (!jsonPromiseCache[key]) {
jsonPromiseCache[key] = new RSVP.Promise(function(resolve, reject){
// If jsonPromiseCached data is not set then make AJAX requiest to get it
var client = new XMLHttpRequest();
client.open("GET", url);
client.onreadystatechange = handler;
client.responseType = "json";
client.setRequestHeader("Accept", "application/json");
client.send();
console.log('---- "client" XMLHttpRequest/AJAX variable ======= ',client);
function handler() {
if (this.readyState === this.DONE) {
// On AJAX success, resolve() our Promise() and set result to cached variable
// to avoid duplicate AJAX requests for this jsonCache[key] Data where "key"
// is used to assign to each AJAX endpoint URL/request of JSON data...
// (milestones, tasks, users, etc...)
if (this.status === 200) {
jsonPromiseCache[key] = this.response;
console.log('---- jsonPromiseCache['+key+'] ====== ',jsonPromiseCache[key]);
// Resolve() the Promise() on AJAX success
resolve(this.response);
// On AJAX failure, reject() our Promise()
}else{
reject(this);
}
}
};
// If JSON data for this key is already jsonPromiseCached, then return the jsonPromiseCached version
// instead of making a new AJAX request!
});
}
return jsonPromiseCache[key];
};
// EXAMPLE USAGE DEMO
// usage loading JSON data with AJAX using Promises
var promises = {
users: getJsonDataPromise('/echo/json/', 'users'),
task: getJsonDataPromise('/echo/json/', 'task')
};
RSVP.hash(promises)
.then(function(results) {
console.log('then() function ran on success of loading JSON data');
console.log(results);
console.log('results.users', results.users); // print the users JSON results
console.log('results.task', results.task); // print the task JSON results
// I want to create another Promise here which will run a function that creates a bunch of DOM Event handlers/listeners and in that function when it is done loading it should fire a success like the above does when JSON data is done loading
})
.finally(function(){
console.log('finally() function ran on success and failure.... It is always ran!');
})
.catch(function(reason){
console.log('[ERROR] REASON:',reason.statusText); //if any of the promises fails.
});
更新
我在此处更新了我的 JSFiddle 演示 http://jsfiddle.net/jasondavis/fttzoggj/2 添加了一个新函数 initDomEvents() 并将其添加到 then(initDomEvents) 调用中。我的控制台显示所有内容都是 运行,正如我所希望的那样,但是由于某种原因,现在我的错误被触发了
您使用 RSVP 的具体原因是什么?我会切换到 jQuery Promises。
var d = $.Deferred;
$.ajax({
url: url,
cache: true,
dataType: 'json',
success: function(data){
d.resolve(data);
},
error: function(error){
d.reject();
}
});
$.when(d).then(function(data){
//handle
});
My console shows all is ran as I want it to however for some reason, now my error is triggered
您的 initDomEvents
函数中没有 resolve
和 reject
函数。它们仅作为 new RSVP.Promise(…)
回调的参数提供。尝试调用它们会引发错误,该错误会被捕获并传播到您的错误处理程序(但它没有 .statusText
属性,因此仅打印 undefined
)。
正如我在评论中所说,如果您的函数不执行任何异步操作,则无需 return 承诺。您只是 return
一个值或 throw
一个异常以及来自您的承诺回调。
如果您坚持围绕结果或拒绝创建承诺,则可以使用 RSVP.Promise.resolve(…)
or RSVP.Promise.reject(…)
函数创建 fulfilled/rejected 个承诺对象。
下面的简单演示 JavaScript 代码使用 RSVP.js Promise 库 https://github.com/tildeio/rsvp.js/ 使用 AJAX 加载一些 JSON 数据,并在完成时触发一些加载所有 JSON 数据后的代码。
我想扩展它以在 JSON 数据加载后执行更多不是 AJAX 请求的承诺。
例如,在 JSON 数据加载后,我想创建另一个 Promise,它将 运行 一个函数,该函数将设置一些 DOM 事件 handlers/listeners。
在设置事件处理的功能之后,我想在事件设置完成后 运行 一些其他功能。
我是新手,仍在学习 Promises,在某些情况下仍在学习 JavaScript,因此我需要一些帮助。在下面和 JSFIddle 上扩展我的示例代码将非常感谢!
我相信如果显示如何向我的演示添加 1 个承诺,那么我在最终应用程序中添加所需的数量就足够了。
以下代码的 JSFIddle 演示:http://jsfiddle.net/jasondavis/fttzoggj/
var jsonPromiseCache = {};
// AJAX function to load JSON data using Promise()
var getJsonDataPromise = function(url, key) {
if (!jsonPromiseCache[key]) {
jsonPromiseCache[key] = new RSVP.Promise(function(resolve, reject){
// If jsonPromiseCached data is not set then make AJAX requiest to get it
var client = new XMLHttpRequest();
client.open("GET", url);
client.onreadystatechange = handler;
client.responseType = "json";
client.setRequestHeader("Accept", "application/json");
client.send();
console.log('---- "client" XMLHttpRequest/AJAX variable ======= ',client);
function handler() {
if (this.readyState === this.DONE) {
// On AJAX success, resolve() our Promise() and set result to cached variable
// to avoid duplicate AJAX requests for this jsonCache[key] Data where "key"
// is used to assign to each AJAX endpoint URL/request of JSON data...
// (milestones, tasks, users, etc...)
if (this.status === 200) {
jsonPromiseCache[key] = this.response;
console.log('---- jsonPromiseCache['+key+'] ====== ',jsonPromiseCache[key]);
// Resolve() the Promise() on AJAX success
resolve(this.response);
// On AJAX failure, reject() our Promise()
}else{
reject(this);
}
}
};
// If JSON data for this key is already jsonPromiseCached, then return the jsonPromiseCached version
// instead of making a new AJAX request!
});
}
return jsonPromiseCache[key];
};
// EXAMPLE USAGE DEMO
// usage loading JSON data with AJAX using Promises
var promises = {
users: getJsonDataPromise('/echo/json/', 'users'),
task: getJsonDataPromise('/echo/json/', 'task')
};
RSVP.hash(promises)
.then(function(results) {
console.log('then() function ran on success of loading JSON data');
console.log(results);
console.log('results.users', results.users); // print the users JSON results
console.log('results.task', results.task); // print the task JSON results
// I want to create another Promise here which will run a function that creates a bunch of DOM Event handlers/listeners and in that function when it is done loading it should fire a success like the above does when JSON data is done loading
})
.finally(function(){
console.log('finally() function ran on success and failure.... It is always ran!');
})
.catch(function(reason){
console.log('[ERROR] REASON:',reason.statusText); //if any of the promises fails.
});
更新
我在此处更新了我的 JSFiddle 演示 http://jsfiddle.net/jasondavis/fttzoggj/2 添加了一个新函数 initDomEvents() 并将其添加到 then(initDomEvents) 调用中。我的控制台显示所有内容都是 运行,正如我所希望的那样,但是由于某种原因,现在我的错误被触发了
您使用 RSVP 的具体原因是什么?我会切换到 jQuery Promises。
var d = $.Deferred;
$.ajax({
url: url,
cache: true,
dataType: 'json',
success: function(data){
d.resolve(data);
},
error: function(error){
d.reject();
}
});
$.when(d).then(function(data){
//handle
});
My console shows all is ran as I want it to however for some reason, now my error is triggered
您的 initDomEvents
函数中没有 resolve
和 reject
函数。它们仅作为 new RSVP.Promise(…)
回调的参数提供。尝试调用它们会引发错误,该错误会被捕获并传播到您的错误处理程序(但它没有 .statusText
属性,因此仅打印 undefined
)。
正如我在评论中所说,如果您的函数不执行任何异步操作,则无需 return 承诺。您只是 return
一个值或 throw
一个异常以及来自您的承诺回调。
如果您坚持围绕结果或拒绝创建承诺,则可以使用 RSVP.Promise.resolve(…)
or RSVP.Promise.reject(…)
函数创建 fulfilled/rejected 个承诺对象。