Javascript 从承诺返回数据
我有一个函数,用于在加载时填充一些字段,如下所示:Javascript 从承诺返回数据,javascript,jquery,promise,Javascript,Jquery,Promise,我有一个函数,用于在加载时填充一些字段,如下所示: function billingAddress(){ var urls = ['myURL']; var output = []; Promise.all( urls.map( u=>fetch(u).then(response => { if (!response.ok) { throw new
function billingAddress(){
var urls = ['myURL'];
var output = [];
Promise.all(
urls.map(
u=>fetch(u).then(response => {
if (!response.ok) {
throw new Error("Http Error " + response.status);
}
return response.json();
})
)
).then(texts => {
fillAddress(texts);
var info = getCustomerInfo(texts);
console.log(info); //returns the data
output.push(info);
});
return output;
}
fillAddress函数只是在加载文档时填充相应的字段。为了下订单,我需要收集客户信息并向服务器发送post请求。我不明白的是如何从getCustomerInfo保存信息,以便以后处理它
供参考
function getCustomerInfo(data){
var temp = data[0]['addresses']['shipping'];
var info = {};
info['address1'] = temp[0];
info['address2'] = temp[1];
info['city'] = temp[2];
info['zip'] = temp[3];
info['country'] = temp[4];
info['state'] = temp[5];
info['phone'] = temp[8];
info['gst'] = temp[9];
info['email'] = temp[10];
info['items'] = [];
return info;
}
职位职能:
function placeOrder(){
var info = billingAddress();
console.log(info); //returns undefined
$.ajax({
url: 'placeOrder',
contentType: 'application/json',
type: 'POST',
dataType: 'json',
data: JSON.stringify(info),
success: function(data){
console.log(data);
}
});
}
placeOrder()是一个onclick函数,因此我无法在billingAddress()中运行它。您正在异步获取
信息
数据,因此必须异步访问它。这意味着您不能返回从同步函数中的异步函数调用获得的值,就像您尝试将info
按到output
然后返回output
一样。函数中发生的情况是,输出
立即作为空数组返回,而异步代码在后台执行,然后更新此数组,但仅在已返回数组之后。相反,您应该从billingAddress
函数返回承诺,并访问承诺回调中的数据:
function billingAddress(){
var urls = ['myURL'];
return Promise.all(
urls.map(
u=>fetch(u).then(response => {
if (!response.ok) {
throw new Error("Http Error " + response.status);
}
return response.json();
})
)
).then(texts => {
fillAddress(texts);
return getCustomerInfo(texts);
});
}
function placeOrder(){
billingAddress().then(info => {
$.ajax({
url: 'placeOrder',
contentType: 'application/json',
type: 'POST',
dataType: 'json',
data: JSON.stringify(info),
success: function(data){
console.log(data);
}
});
});
}
此外,我建议使用const
或let
而不是var
和async/await
来处理您的承诺,这将产生更干净的代码:
async function billingAddress(){
try {
const urls = ['myURL'];
const texts = await Promise.all(
urls.map(u => {
const response = await fetch(u);
if (!response.ok) {
throw new Error("Http Error " + response.status);
}
return response.json();
})
);
return getCustomerInfo(fillAddress(texts));
} catch (e) {
// handle errors
}
}
async function placeOrder(){
try {
const info = await billingAddress();
$.ajax({
url: 'placeOrder',
contentType: 'application/json',
type: 'POST',
dataType: 'json',
data: JSON.stringify(info),
success: function(data){
console.log(data);
}
});
} catch (e) {
// handle errors
}
}
他不能也使用async/await吗?@JoelHager绝对可以,但这不会改变代码是否是异步的。从这段代码中使用的
var
判断,我不确定ES标准OP使用的是什么这对我来说很好。我正试图了解js的异步特性。谢谢大家!@megadarkfriend没问题,我还使用JoelHagerWell建议的async/await
语法添加了一个编辑,它的await
部分在技术上类似于同步逻辑。这就是我想说的全部