gpt4 book ai didi

javascript - 使用 promises 链接多个 ajax 请求

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:32:47 24 4
gpt4 key购买 nike

我希望链接多个 ajax 请求,大致如下:获取第一个 JSON,如果成功,则继续获取第二个 JSON,如果成功,则创建一个包含两个 JSON 数据的新对象。

// get first json
$.getJSON('http://www.json1.com').then(function(json1){
return json1
}).then(function(json1){
// get second json
$.getJSON('http://www.json2.com').then(function(json2){
var both = {}
both.one = json1
both.two = json2
return both
})
})

我应该将 .then 语句相互嵌套吗?我不完全确定如何获取 both 变量。

最佳答案

.then(function(json1){
return json1
})

这是一个不必要的(几乎)身份调用。

.then(function(json1){
…;

您应该始终从 then 回调中return,以便新的 promise 获得一个值。您甚至可以返回将被“展开”的 promise !

Should I be nesting .then statements in each other?

嵌套或链接它们并不重要,那就是 the great thing about promises .链接它们会降低“金字塔”的高度,因此它被认为更干净,但是您无法从更高的范围访问变量。在您的情况下,您需要访问 json1,因此您必须嵌套它们。

I'm not completely sure how to get the both variable.

当您从回调中执行 return 时,您可以将其作为从 then 调用中返回的 promise 的解析值。

$.getJSON('http://www.json1.com').then(function(json1){
return $.getJSON('http://www.json2.com').then(function(json2){
return {one: json1, two: json2};
})
}).then(function(both) {
// do something with both!
});

关于javascript - 使用 promises 链接多个 ajax 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23667254/

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