【发布时间】:2019-04-05 22:06:01
【问题描述】:
Edit2:底部的解决方案
我正在使用 chrome-console 并且我正在尝试输出获取的数据,并且我只能通过在正确的位置写入“await”来获得所需的输出,即使另一个解决方案可以更早地做到这一点而且我没有知道它为什么/如何工作。
solution() 是我正在做的网络课程的“官方”解决方案。 目前两个函数返回相同。 在 myFunction 中,我尝试在每个使用的函数前面写“await”,并使每个函数“异步”,但我仍然无法替换日志中的“await” ,即使其他解决方案可以。
const urls = ['https://jsonplaceholder.typicode.com/users']
const myFunction = async function() {
// tried await before urls/fetch (+ make it async)
const arrfetched = urls.map( url => fetch(url) );
const [ users ] = arrfetched.map( async fetched => { //tried await in front of arrfetched
return (await fetched).json(); //tried await right after return
});
console.log('users', await users); // but can't get rid of this await
}
const solution = async function() {
const [ users ] = await Promise.all(urls.map(async function(url) {
const response = await fetch(url);
return response.json();
}));
console.log('users', users); // none here, so it can be done
}
solution();
myFunction();
我认为“等待”的工作方式是:
const a = await b;
console.log(a); // this doesn't work
同
const a = b;
console.log(await a); // this works
但它没有,我不明白为什么不。我觉得 Promise.all 做了一些意想不到的事情,因为简单地在声明中写“等待”不能做同样的事情,只有在声明之后。
Edit1:这不起作用
const myFunction = async function() {
const arrfetched = await urls.map( async url => await fetch(url) );
const [ users ] = await arrfetched.map( async fetched => {
return await (await fetched).json();
});
console.log('users', users);
}
Edit2: 感谢大家的帮助,我尝试将“.toString()”放在很多变量上,并切换我在代码中放置“await”的位置哪里没有。 据我了解,如果我不使用 Promise.all,那么每次我想使用(如在实际数据中,而不仅仅是使用)具有承诺的函数或变量时,我都需要等待强>。仅在正在处理数据的地方等待而不进一步向上是不够的。 在上面的 Edit1 中,用户在任何其他等待完成之前运行,因此无论我写了多少等待,都没有执行。在(在我的情况下是 chrome-)控制台中复制此代码可以很好地演示它:
const urls = [
'https://jsonplaceholder.typicode.com/users',
]
const myFunction = async function() {
const arrfetched = urls.map( async url => fetch(url) );
const [ users ] = arrfetched.map( async fetched => {
console.log('fetched', fetched);
console.log('fetched wait', await fetched);
return (await fetched).json();
});
console.log('users', users);
console.log('users wait', await users);
}
myFunction();
// Output in the order below:
// fetched()
// users()
// fetched wait()
// users wait()
【问题讨论】:
-
不清楚你想要达到什么目的。
-
我想像这样摆脱 myFunction 控制台中的等待:console.log('users', users);
-
你在这里让事情变得过于复杂。在您的“edit1”中,您正在使用
async await解析一组承诺,然后,您将该数组映射为实际上假装将await加倍已经解决的问题。如果fetch返回Promise,则first.map应该是异步的。如果.json()返回Promise,那么第二个也应该是异步的。然而,真正的await应该发生在fetch操作上,而不是其他任何事情上。 -
那么等待比必要的更多会破坏其他工作代码吗?
-
只是为了澄清这一点(除了我的回复):额外的
await永远不会有害(除了性能方面)。等待一个非承诺,例如await 'hello'会先把它变成一个 Promise 然后等待它,所以它等价于await Promise.resolve('hello')
标签: javascript promise async-await