【发布时间】:2021-04-10 11:56:11
【问题描述】:
观看视频并阅读 [Promise.then][1] 后,我仍然不明白它是如何工作的。 所以我写了一个例子,并打印到控制台但仍然输出我无法理解它是如何工作的。 我希望我的问题足够清楚,如果没有,请告诉我,我会根据您的回答尝试详细说明。 这是我的代码:
const getCountryData = function (country) {
fetch(`https://restcountries.eu/rest/v2/name/${country}`)
.then(response => {
console.log('111111111111111');
if (!response.ok)
throw new Error(`Country not found (${response.status})`);
return response.json();
})
.then(data => {
console.log('22222222222');
const neighbour = data[0].borders[0];
if (!neighbour) return;
return fetch(`https://restcountries.eu/rest/v2/alpha/${neighbour}`);
})
.then(response => {
console.log('333333333')
if (!response.ok)
throw new Error(`Country not found (${response.status})`);
return response.json();
})
.then(data => console.log('44444444444'))
.catch(err => {
console.error(`${err} ????????????`);
})
.finally(() => {
console.log('finalyyyy')
});
console.log("after all async calls");
};
我无法理解以下内容:
- 如果我们在第一个 then 上查找示例,它会获取一个回调作为参数,该回调返回一个 Promise 对象。哪个对象调用第二个then?是从第一次调用 when 时返回的还是从回调中返回的?
- 我知道回调是“附加”到 fetch 函数的。例如,当 fetch 函数完成时,回调将被执行。 但是我不明白第二个、第三个和第四个 then 的调用方式和时间。第一个回调还包含一个异步函数** response.json()**,所以如果他需要 ,second when 将如何以及何时启动json.response 从第一个 when?
- 如果第一次或第二次发生异常,代码如何知道跳转到catch函数?
[1]:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then
【问题讨论】:
-
"然后哪个对象调用第二个?" - 没有“对象”调用它。 您的代码 在一个对象上调用该方法 - 在您的代码中,这是第一个
.then()调用返回的承诺。 "已经从回调中返回的那个?" - 调用第二个.then()时回调还没有执行,所以它不能是返回值 -
我阅读了两个链接,但仍然无法理解一些内容。 1.是否所有
when方法都立即执行,无需等待回调先运行? 2.第一个回调返回的值是第二个回调输入(不完全是因为它从'Promise'中取出值)? -
这是实现承诺的值,通常传递给承诺的
resolve()函数。这取决于如何构建承诺。如果它是由(返回).then(res => …)调用构造的承诺,是的,它通过回调的返回值解决。但是,resolving means that promises are recursively unwrapped,所以如果你从then回调返回一个承诺,外部承诺最终将通过内部承诺的 result 实现。
标签: javascript asynchronous promise