我已经将我的代码重组为承诺,并构建了一个由多个回调组成的精彩长扁平承诺链.then().最后我想返回一些复合值,并且需要访问多个中间承诺结果.但是,序列中间的分辨率值不在最后一个回调的范围内,我该如何访问它们?
function getExample() {
return promiseA(…).then(function(resultA) {
// Some processing
return promiseB(…);
}).then(function(resultB) {
// More processing
return // How do I gain access to resultA here?
});
}
Run Code Online (Sandbox Code Playgroud) 我已经开发了几年的JavaScript,我根本不理解有关承诺的大惊小怪.
似乎我所做的只是改变:
api(function(result){
api2(function(result2){
api3(function(result3){
// do work
});
});
});
Run Code Online (Sandbox Code Playgroud)
无论如何,我可以使用像async这样的库,例如:
api().then(function(result){
api2().then(function(result2){
api3().then(function(result3){
// do work
});
});
});
Run Code Online (Sandbox Code Playgroud)
哪个代码更多,可读性更低.我没有在这里获得任何东西,它也不会突然神奇地"平坦".更不用说必须将事物转换为承诺.
那么,这里的承诺有什么大惊小怪?
如果我有一个网址数组:
var urls = ['1.txt', '2.txt', '3.txt']; // these text files contain "one", "two", "three", respectively.
Run Code Online (Sandbox Code Playgroud)
我想构建一个如下所示的对象:
var text = ['one', 'two', 'three'];
Run Code Online (Sandbox Code Playgroud)
我一直在努力学习如何做到这一点fetch,这当然会回归Promises.
有些事情我已经试过了不工作:
var promises = urls.map(url => fetch(url));
var texts = [];
Promise.all(promises)
.then(results => {
results.forEach(result => result.text()).then(t => texts.push(t))
})
Run Code Online (Sandbox Code Playgroud)
这看起来不对,无论如何它都不起作用 - 我最终没有数组['one','two','three'].
Promise.all在这里使用正确的方法?
从具有JavaScript fetch API的服务器请求时,您必须执行类似的操作
fetch(API)
.then(response => response.json())
.catch(err => console.log(err))
Run Code Online (Sandbox Code Playgroud)
在这里,response.json()正在解决它的承诺.
问题是,如果你想捕获404错误,你必须解决响应承诺,然后拒绝获取承诺,因为只有在catch出现网络错误时你才会结束.所以fetch调用就像是
fetch(API)
.then(response => response.ok ? response.json() : response.json().then(err => Promise.reject(err)))
.catch(err => console.log(err))
Run Code Online (Sandbox Code Playgroud)
这是一个更难阅读和推理的东西.所以我的问题是:为什么需要这个?将承诺作为回应价值有什么意义?有没有更好的方法来处理这个?
我刚刚开始学习Fetch API:https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
这是我编写的代码片段,用来修补它:
fetch('http://swapi.co/api/people/1')
.then(function(response) {
var json = response.json();
console.log(json);
// Expected : { "name": "Luke Skywalker","height": "1.72 m", ... }
// Get : Promise {[[PromiseStatus]]: "pending", [[PromiseValue]]: undefined}
});
Run Code Online (Sandbox Code Playgroud)
我本来希望从response.json()中获取一个JSON对象.
与使用JSON.parse()时获得的内容类似.
相反,我得到了一个承诺对象.
如果我扩大这里显示的承诺链......
return response.json().then(function(json) {
// process your JSON further
});
Run Code Online (Sandbox Code Playgroud)
...然后它工作:在以下承诺的then方法中,它显示为json.
为什么我不能在第一个promise的then()中检索JSON数据?
谁能请解释这里发生了什么?
我真的很感激.
我正在尝试使用电影数据库中的多个数据对象Promise.all.在我遍历fetch调用的所有结果并使用.json()每一位数据后,我尝试将其记录到控制台.但是,我得到的是一个数组,而不是带有数据的对象数组Promises.嵌套在promises中,我可以看到我的数据,但我显然错过了一个步骤,以便拥有一组数据对象,而不仅仅是Promises.
我在这里错过了什么?
//store movie API URLs into meaningful variables
const trending = `https://api.themoviedb.org/3/trending/all/day?api_key=${API_KEY}`;
const topRated = `https://api.themoviedb.org/3/movie/top_rated?api_key=${API_KEY}&language=en-US&page=1`;
const nowPlaying = `https://api.themoviedb.org/3/movie/now_playing?api_key=${API_KEY}&language=en-US&page=1`;
const upcoming = `https://api.themoviedb.org/3/movie/upcoming?api_key=${API_KEY}&language=en-US&page=1`;
//create an array of urls to fetch data from
const allMovieURLs = [trending, topRated, nowPlaying, upcoming];
const promiseURLs = allMovieURLs.map(url => fetch(url));
Promise.all(promiseURLs)
.then(responses => responses.map(url => url.json()))
.then(dataArr => console.log(dataArr));
};
Run Code Online (Sandbox Code Playgroud) fetch API 请求只会在出现网络或服务器错误时失败。因此,例如,如果我执行以下代码,假设它通过try块没有错误,我将有一个有效的填充res.
try {
const res = await fetch('/createurl', {
method: 'POST',
body: 'testData',
headers: {
'Content-Type': 'application/json'
}
})
if (res.ok) {
alert('Resource created!')
} else {
alert('Error creating resource!')
}
flashResponseToUser(res)
} catch(e) {
alert('A server or network error occurred during the request!')
}
Run Code Online (Sandbox Code Playgroud)
我正在处理res向用户显示使用该功能的必要信息error或success消息flashResponseToUser(res)。由于res.json()返回 a Promise,flashResponseToUser必须是一个异步函数。
const flashResponseToUser = async(res) => {
const jsonRes = await res.json() // Get …Run Code Online (Sandbox Code Playgroud) 我使用jsonplaceholder URL测试fetch API,但我的函数返回"Promise State:Pending",我不明白为什么:
function getUsers(url) {
return fetch(url)
}
const users = getUsers(`https://jsonplaceholder.typicode.com/users`);
users.then(response => {
console.log(response.text());
});
Run Code Online (Sandbox Code Playgroud)
我认为问题是因为异步/同步方法?
我一直在关注教程并遇到以下代码片段:
const myAsyncFunction = async () => {
const usersResponse = await fetch(
'https://jsonplaceholder.typicode.com/users'
)
const userJson = await usersResponse.json();
const secondUser = userJson[1];
console.log(secondUser);
const posts = await fetch (
'https://jsonplaceholder.typicode.com/posts?userId=' + secondUser.id
);
const postsJson = await posts.json();
console.log(postsJson);
}
myAsyncFunction();
Run Code Online (Sandbox Code Playgroud)
是否应该立即将响应转换为 JSON 对象,就像从数组中获取值userJson[1]一样?为什么需要await usersResponse.json()和posts.json()?
我试图理解承诺,所以我在 twitch 上尝试了一个简单的 get 请求。我不明白的是为什么会json()返回一个承诺。为什么 ?响应中已经包含数据,那么为什么它是一个承诺?
fetch('https://api.twitch.tv/kraken/games/top?limit=10&offset=0')
.then( resp => {
resp.json()
.then(function(data) {
console.log(data);
});
});
Run Code Online (Sandbox Code Playgroud)
换句话说:第一个then,我理解,它等待响应。然而,当进入 then 函数时,这意味着已经收到响应,因此数据应该可以立即访问,而无需另一个承诺。它只是让我感到困惑。
我从 JS 开始,实际上喜欢异步方面(来自 Python),但我不确定为什么有些函数会返回 Promise。具体来说,下面的代码 usingfetch让我想知道返回的是什么json():
fetch('https://freegeoip.net/json/8.8.8.8')
.then((response) => {
return response.json()
})
.then((json) => {
Object.keys(json).forEach((key) => {
console.log("got " + key)
})
})Run Code Online (Sandbox Code Playgroud)
撇开流不谈,我们在 a 之后得到的 HTTP 响应GET是一个文本块,稍后由客户端解释以提取标头、正文和其他有趣的元素 - 作为 HTTP 内容分析的一部分。
关键是这个文本块是一个整体,所以第一个then()已经有了整个响应——为什么解析 JSON 正文是一个异步操作,forEach与第二个不同then()?
换句话说,为什么我不能让以下代码工作?
fetch('https://freegeoip.net/json/8.8.8.8')
.then((response) => {
Object.keys(response.json()).forEach((key) => {
console.log("got " + key)
})
})Run Code Online (Sandbox Code Playgroud)
注意:如果第一个代码运行不正确(带有ERR_BLOCKED_BY_CLIENT),请尝试禁用您的广告拦截器。第二个是故意不正确的。
所以我的代码在这里返回一个Promise,因为我使用then语法,我不知道为什么会发生这种情况: - ??
fetch('someurltoAJsonFile.json')
.then(function(response) {
console.log(response.json());});
Run Code Online (Sandbox Code Playgroud) 这是我的提取功能:
getAllCountries = async () => {
try {
const response = await fetch("https://restcountries.eu/rest/v2/all");
const result = response.json();
console.log(result);
this.countriesList = result;
} catch (error) {
console.log(error);
}
};
Run Code Online (Sandbox Code Playgroud)
为什么在那里登录了两个 Promise,以及如何访问 PromiseResult。我试过了,console.log(result[0])但没有用
javascript ×13
promise ×6
fetch-api ×5
json ×5
ecmascript-6 ×3
es6-promise ×3
fetch ×3
asynchronous ×2
bluebird ×2
api ×1
async-await ×1
callback ×1
q ×1
scope ×1