猿问

JS'await 仅在 Promise.all() 函数中的异步函数中有效

我正在尝试使用 Promise.all() 函数对所有请求进行等待,而不是像这样手动执行所有获取:


var data = await Promise.all([

        fetch('https://jsonplaceholder.typicode.com/posts').then((response) => response.json()),

        fetch('https://jsonplaceholder.typicode.com/albums').then((response) => response.json()),

        fetch('https://jsonplaceholder.typicode.com/users').then((response) => response.json())

      ]);

我想让它动态化,像这样发出 N 个获取请求:


       let promiseList = [];

        try {

            for (let url of requestUrls) {

                promiseList.push(fetch(url).then((response) => response.json()));

            }


            var data = await Promise.all(promiseList);

但我得到这个错误Uncaught SyntaxError: await is only valid in async function的await Promise.all()路线,如果我删除的await,我得到一个Promise {<pending>}和 (index):79 error:TypeError: data is not iterable


这是我的完整代码:https : //jsfiddle.net/ham7g82e/1/


从这些提取中获取数据我缺少什么?


DIEA
浏览 325回答 3
3回答

皈依舞

不要使用 await,而是使用 Promise.thenPromise.all(promiseList).then(data => {&nbsp; document.getElementById("result").innerHTML = data;&nbsp; console.log(data);&nbsp; for (var i of data) {&nbsp; &nbsp; console.log(`RESPONSE ITEM \n`);&nbsp; &nbsp; &nbsp; for (var obj of i) {&nbsp; &nbsp; &nbsp; &nbsp; console.log(obj);&nbsp; &nbsp; &nbsp; }&nbsp; }});

慕村225694

要使用 await,它需要是异步函数的一部分。async function functionName() {&nbsp;//You can use await in here, because you used the async keyword}

www说

如果执行此代码的函数不是异步的,您可以使用 .then() 从承诺中获取值。不需要使用等待。
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答