将提取调用到提取的承诺中是一种不好的做法?
Calling a fetch into a fetch's promise is a bad practice?
我正在接受 fetch() 的使用培训。
正如您在下面的代码中看到的那样,我决定将一次提取放入第一次提取的承诺中,但即使该代码工作正常,我也不确定这是好事还是坏事。
如果编写的代码是一种不好的做法,有人可以告诉我好的代码吗?
提前致谢。
function callOne () {
let q = 'q='+input.value;
fetch(urlOne)
.then(res => res.json())
.then(data => {
console.log(data);
callTwo(q);
})
.catch(err => {
console.log(err);
});
}
function callTwo(q) {
fetch(urlTwo)
.then(res => res.json())
.then(data => {
console.log(data);
})
.catch(err => {
console.log(err);
});
}
这取决于,当它们像在您的代码中一样独立时,您可以 运行 它们并行。类似于:
Promise.all([callOne(), callTwo()]).then(([dataOne, dataTwo]) => {/**/})
这样就不会嵌套了,可以更好的维护它们。并且会完成得更快。但是,如果您必须等待第一个数据传递给第二个数据,那么您就必须像以前那样做。虽然,我想我会这样写:
callOne()
.then(/*do something with first response and pass to second call*/)
.then(callTwo)
.then(/*do something with second data*/)
在这两种情况下,如果在您的调用函数中 return 提取会更好。 return fetch(...).then(...).catch(...)
这样您就可以像通常那样链接承诺。 callOne().then(...)
我正在接受 fetch() 的使用培训。
正如您在下面的代码中看到的那样,我决定将一次提取放入第一次提取的承诺中,但即使该代码工作正常,我也不确定这是好事还是坏事。
如果编写的代码是一种不好的做法,有人可以告诉我好的代码吗?
提前致谢。
function callOne () {
let q = 'q='+input.value;
fetch(urlOne)
.then(res => res.json())
.then(data => {
console.log(data);
callTwo(q);
})
.catch(err => {
console.log(err);
});
}
function callTwo(q) {
fetch(urlTwo)
.then(res => res.json())
.then(data => {
console.log(data);
})
.catch(err => {
console.log(err);
});
}
这取决于,当它们像在您的代码中一样独立时,您可以 运行 它们并行。类似于:
Promise.all([callOne(), callTwo()]).then(([dataOne, dataTwo]) => {/**/})
这样就不会嵌套了,可以更好的维护它们。并且会完成得更快。但是,如果您必须等待第一个数据传递给第二个数据,那么您就必须像以前那样做。虽然,我想我会这样写:
callOne()
.then(/*do something with first response and pass to second call*/)
.then(callTwo)
.then(/*do something with second data*/)
在这两种情况下,如果在您的调用函数中 return 提取会更好。 return fetch(...).then(...).catch(...)
这样您就可以像通常那样链接承诺。 callOne().then(...)