gpt4 book ai didi

javascript - 第二个 promise 无法正常工作

转载 作者:行者123 更新时间:2023-12-03 04:10:24 24 4
gpt4 key购买 nike

我有以下完美运行的 promise :

self.getAll = function (callback) {
var users= [];
var promises = [];
$.ajax({
url: "/API/Users",
type: "GET",
success: function (results) {
var mappedContacts = $.map(results, function (item) {
promises.push($.ajax({
url: "/API/Users/contacts/" + item.id,
type: "GET"
}).then(function (contacts) {
users.push(new User(item, contacts));
}));
});
$.when.apply($, promises).then(function () {
callback(users);
});
}
});
}

我正在尝试添加第二个 AJAX 请求,但它无法正常工作:

self.getAll = function (callback) {
var users= [];
var promises = [];
$.ajax({
url: "/API/Users",
type: "GET",
success: function (results) {
var mappedContacts = $.map(results, function (item) {
promises.push($.ajax({
url: "/API/Users/contacts/" + item.id,
type: "GET"
}).then(function (contacts) {
users.push(new User(item, contacts));
}));
});
var mappedContacts2 = $.map(results, function (item) {
promises.push($.ajax({
url: "/API/Users/contacts2/" + item.id,
type: "GET"
}).then(function (contacts2) {
users.push(new User(item, "",contacts2));
}));
});
$.when.apply($, promises).then(function () {
callback(users);
});
}
});
}

contacts2 始终为空,我做错了什么?

这是User对象:

var User= function (data, contacts, contacts2) {
this.id = ko.observable(data.id);
this.name = ko.observable(data.name);
this.contacts = ko.observableArray(contacts);
this.contacts2 = ko.observableArray(contacts2 );
}

最佳答案

由于您需要将每个用户的两组联系人传递给 new User(),因此请使用一个返回 $.when() 的 map() 对于两个联系人请求。在 $.when()

then() 中创建用户

类似于:

self.getAll = function(callback) {
var users = [];
// return this promise ..... see notes below
return $.getJSON("/API/Users").then(results) {

// map array of promises to pass to final $.when
var promises = $.map(results, function(item) {

var req1 = $.getJSON("/API/Users/contacts/" + item.id);
var req2 = $.getJSON("/API/Users/contacts2/" + item.id);

// return this promise to mapped array
return $.when(req1, req2).then(function(contacts1, contacts2) {
// create user now that we have both sets of contacts
users.push(new User(item, contacts1, contacts2));
});
})

// should return this promise .... see notes below
return $.when.apply($, promises).then(function() {
callback(users);
// return `users` ...see notes below
});

})
}

当您只需返回上面注释中显示的 promise 链并执行以下操作时,使用回调是一种过时的方法:

self.getAll().then(function(users) {
// do something with users
})

关于javascript - 第二个 promise 无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44356847/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com