简体   繁体   English

Promise.所有返回 function

[英]Promise.all returns function

I would like use Async/Await with fetch API. So, i've 2 async function for return result.json() .我想将 Async/Await 与 fetch API 一起使用。因此,我有 2 个 async function 用于return result.json()

I add my 2 Promise in Promise.all([]) , but the values returned is 'function()'.我在Promise.all([])中添加了我的 2 Promise,但返回的值是“function()”。

My code:我的代码:

  // Load external users
  const externalUsers = async () => {
    const result = await fetch(url);
    return result.json();
  };

  const localUsers = async () => {
    const result = await Users.allDocs({ include_docs: true });
    return result.rows;
  };

  Promise.all([externalUsers, localUsers]).then(values => {
    console.log(values); // return (2) [function, function]
  });

I don't understand why.我不明白为什么。 Can you help me?你能帮助我吗?

Thank you community !谢谢社区!

Run your functions in the Promise.all .Promise.all中运行你的函数。 So they will return Promises which will be settled and passed to the then function.所以他们将返回 Promises,这些 Promises 将被解决并传递给then函数。

Promise.all([externalUsers(), localUsers()]).then(values => {
    console.log(values);
});

You should await your Promise.all你应该await你的Promise.all

const values = await Promise.all([...]);
const value1 = values[0];
...

The reason you are seeing functions, is because Promise.all returns a Promise that resolves to an array.您看到函数的原因是因为Promise.all返回一个解析为数组的 Promise。 So by await ing the Promise.all , you wait for them all to finish/resolve first.因此,通过await Promise.all ,您首先等待它们全部完成/解决。

You can also do,你也可以这样做,

const [externalUsersResult, localUsersResult] = await Promise.all([externalUsers, localUsers])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM