gpt4 book ai didi

javascript - 在 JS 对象中异步加载数据

转载 作者:行者123 更新时间:2023-11-28 09:17:36 25 4
gpt4 key购买 nike

我目前正在为我的网上商店应用程序编写一个 JS 类,以访问存储在服务器上的产品信息。信息应该异步加载。为此,我使用 dojo.xhrPost() 。我想为这个类重写一个函数,名为 getProductName(productId:int):String它返回给定产品 ID 的产品名称。该函数使用 intern dojo.xhrPost() 。但是我应该返回加载的产品名称吗,因为我必须传递新函数来加载并在 dojo.xhrPost() 中出现错误。 ?

该函数的用法:其他JS函数调用该函数加载商品名称来更新购物车网页,而无需重新加载整个页面。返回的数据为 JSON 格式,因为需要传输一些附加信息以进行错误处理(客户端函数必须知道服务器端是否发生任何错误)。

函数代码 getProductName(productId:int) :

      function getProductName(productId) {
dojo.xhrPost({
url: '/shop/dataProduct.php',
handleAs: 'json',
content: {productId:productId},
load: function(response, ioArgs) {
if (!response.error) {
// here I would like to return response.data to the caller of myObj.getProductName(productId)
} else {
// here I would like to return "error" to the caller of myObj.getProductName(productId)
}
return response;
},
error: function(response, ioArgs) {
// here I would like to return "error" to the caller of myObj.getProductName(productId)
return response;
}
});
}

用法:

           var productName = myObj.getProductName(5);

最佳答案

以下代码行的问题在于它假设产品名称的检索是同步的。但是您正在进行 ajax 调用来获取名称,因此代码是异步的。

var productName = myObj.getProductName(5);

您需要使用dojo/Deferred来处理异步调用。

function getProductName(productId) {

var d = new dojo.Deferred();

dojo.xhrPost({
url: '/shop/dataProduct.php',
handleAs: 'json',
content: {productId:productId},
load: function(response, ioArgs) {
if (!response.error) {
var productName = ???;
d.resolve(productName);
} else {
d.reject(response.error);
}
},
error: function(err) {
d.reject(err);
}
});

return d;
}

用法:

getProductName(1).then(
function(productName) {
// do something with product name

}, function(error) {
// handle error
});

http://dojotoolkit.org/reference-guide/1.8/dojo/Deferred.html

关于javascript - 在 JS 对象中异步加载数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15448058/

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