javascript - 从 Promise 返回数据
问题描述
我有一个函数用于在加载时填充一些字段,如下所示:
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 函数只是在文档加载时填写相应的字段。为了下订单,我需要收集客户信息并向服务器发送发布请求。我不明白如何保存来自 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
异步获取数据,因此您必须异步访问它。这意味着您不能返回从同步函数中的异步函数调用获得的值,就像您尝试推info
送到output
然后返回一样output
。您的函数中发生的事情output
是立即作为空数组返回,而您的异步代码在后台执行,然后更新此数组,但仅在它已经返回之后。相反,你应该从你的billingAddress
函数中返回一个 Promise 并访问 Promise 回调中的数据:
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
orlet
代替var
andasync/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
}
}
推荐阅读
- javascript - 如何从 node.js 更改 HTML 元素的值
- javascript - 为什么我无法在 AJAX 中获取表数据?每次我从表中获取 req_id 时,它都会在 Console.log 中给我未定义的值
- sql - 在 .Net Core 3.1 Web API 中将文档上传到 SQL Server 时出错
- java - 按钮不显示连接到它的框架
- r - 如何向下滚动页面直到完全加载?
- c# - 在调试中运行时部署程序中的 ServiceClient Null-Exeption
- python - 在 Pycharm 中导入 numpy 或 pandas 时,“进程以退出代码 132 完成(被信号 4:SIGILL 中断)”
- python - 对齐和填充不同长度和分辨率的数字列表的方法
- sysml - 客串和 UPDM 2
- arrays - 用脚本替换受保护范围内的用户(Google Sheet)