在 javascript 中使用这样的代码是否明智?
是的。您的代码很好。
除了第二次请求之后,
fetch(anotherUrl).then(function(response) {,
我会替换return response.json();
与response.json().then(function(data2) { - 就像在
第一个请求。
然后变量data2 将包含内部的响应主体
URL 请求,根据需要。
这意味着 – 无论您想对 data2 做什么,您都必须这样做
在第二个回调中(因为您没有返回承诺。)
此外,再打印几份将有助于了解正在发生的事情。
1。原始代码——稍作修改
进行这些更改后,这是一个堆栈片段,其中包含您的
代码:
1
const url = 'https://jsonplaceholder.typicode.com/todos/1';
const anotherUrl = 'https://jsonplaceholder.typicode.com/todos/4';
fetch(url, {
method: 'get'
}).then(function (response) {
response.json().then(function (data) {
console.log('Response body of outer "url":');
console.log(JSON.stringify(data) + '\n\n');
fetch(anotherUrl).then(function (response) {
response.json().then(function (data2) {
console.log('Response body of inner "anotherUrl":');
console.log(JSON.stringify(data2) + '\n\n');
});
}).catch(function () {
console.log('Booo');
});
});
})
.catch(function (error) {
console.log('Request failed', error);
});
.as-console-wrapper { max-height: 100% !important; top: 0; }
真的很好,虽然胖箭头风格更常见
这些天来定义一个函数。
2。代码重构
这是您的代码的重构版本。
它有一个内部 chained/nested 请求 – fetch(urlInner) –
取决于从先前/外部请求中检索到的数据:fetch (urlOuter)。
通过返回外部和内部 URL 获取的承诺,
稍后可以在代码中访问/解决承诺的结果:
2
const urlOuter = 'https://jsonplaceholder.typicode.com/todos/1';
let urlInner = '';
const resultPromise = fetch(urlOuter)
.then(responseO => responseO.json())
.then(responseBodyO => {
console.log('The response body of the outer request:');
console.log(JSON.stringify(responseBodyO) + '\n\n');
const neededValue = responseBodyO.id + 3;
urlInner = 'https://jsonplaceholder.typicode.com/todos/' + neededValue;
console.log('neededValue=' + neededValue + ', URL=' + urlInner);
return fetch(urlInner)
.then(responseI => responseI.json())
.then(responseBodyI => {
console.log('The response body of the inner/nested request:');
console.log(JSON.stringify(responseBodyI) + '\n\n');
return responseBodyI;
}).catch(err => {
console.error('Failed to fetch - ' + urlInner);
console.error(err);
});
}).catch(err => {
console.error('Failed to fetch - ' + urlOuter);
console.error(err);
});
resultPromise.then(jsonResult => {
console.log('Result - the title is "' + jsonResult.title + '".');
});
.as-console-wrapper { max-height: 100% !important; top: 0; }
请注意,缩进的深度不能超过 8 个空格。
3。这种代码风格的优点
这显然是一种嵌套的代码编写方式——意味着
链式请求fetch(urlInner) 缩进并在
第一个请求的回调fetch(urlOuter)。
然而,缩进树是合理的,这种风格很能引起共鸣
根据我对链接请求的直觉。 – 但更重要的是,
这种风格使得编写精确定位的错误消息成为可能
哪个 URL 失败。
运行下面的 sn -p 以查看错误消息如何表明它是
导致错误的内部/第二个 URL:
const urlOuter = 'https://jsonplaceholder.typicode.com/todos/1';
let urlInner = '';
const resultPromise = fetch(urlOuter)
.then(responseO => responseO.json())
.then(responseBodyO => {
console.log('The response body of the outer request:');
console.log(JSON.stringify(responseBodyO) + '\n\n');
const neededValue = responseBodyO.id + 3;
urlInner = 'https://VERY-BAD-URL.typicode.com/todos/' + neededValue;
console.log('neededValue=' + neededValue + ', URL=' + urlInner);
return fetch(urlInner)
.then(responseI => responseI.json())
.then(responseBodyI => {
console.log('The response body of the inner/nested request:');
console.log(JSON.stringify(responseBodyI) + '\n\n');
return responseBodyI;
}).catch(err => {
console.error('Failed to fetch - ' + urlInner);
console.error(err);
});
}).catch(err => {
console.error('Failed to fetch - ' + urlOuter);
console.error(err);
});
resultPromise.then(jsonResult => {
console.log('Result - the title is "' + jsonResult.title + '".');
});
.as-console-wrapper { max-height: 100% !important; top: 0; }
4。展平所有出现的.then()?
在他人的启发下,您可能会倾向于将所有出现的
.then(),如下图。
我会建议反对这样做——或者至少三思而后行
正在做。为什么?
- 在没有错误的情况下,没关系。
- 如果有有个错误,这样的样式会导致不太明显的错误
消息:
const urlOuter = 'https://jsonplaceholder.typicode.com/todos/1';
let urlInner = '';
const resultPromise = fetch(urlOuter)
.then(responseO => responseO.json())
.then(responseBodyO => {
console.log('The response body of the outer request:');
console.log(JSON.stringify(responseBodyO) + '\n\n');
const neededValue = responseBodyO.id + 3;
urlInner = 'https://VERY-BAD-URL.typicode.com/todos/' + neededValue;
console.log('neededValue=' + neededValue + ', URL=' + urlInner);
return fetch(urlInner);
})
.then(responseI => responseI.json())
.then(responseBodyI => {
console.log('The response body of the inner/nested request:');
console.log(JSON.stringify(responseBodyI) + '\n\n');
return responseBodyI;
}).catch(err => {
console.error('Failed to fetch one or more of these URLs:');
console.log(urlOuter);
console.log(urlInner);
console.log(err);
});
.as-console-wrapper { max-height: 100% !important; top: 0; }
代码很平坦,但最后捕获的错误无法决定
哪些 URL 请求失败。
1 此答案的所有 sn-ps 均符合
JavaScript Semistandard Style.
2 关于第 11 行 – return fetch(urlInner) – 它是
非常很容易忘记return 获取。
(我曾经忘记它,甚至在写完这个答案之后。)
如果您确实忘记它,resultPromise 将不会包含任何承诺
全部。
然后 sn-p 中的最后三行将失败——它们将输出
什么都没有。
结果完全失败!