for await给出SyntaxError:异步函数内的意外保留字

时间:2019-12-04 20:24:20

标签: javascript async-await azure-storage-blobs

这是我的引发异常的代码。无法弄清楚为什么会说“意外保留字”。 main()函数是异步类型。上面的代码行没有抱怨。

const { BlobServiceClient } = require("@azure/storage-blob");
async function main() {
    try {
        const blobServiceClient = await BlobServiceClient.fromConnectionString('some string');
        let i = 1;
        const result = await blobServiceClient.listContainers();
        for await (const container of result) {
            console.log(`Container ${i++}: ${container.name}`);
        }
    } catch (error) {
        console.log(error);
    }
}

main();

2 个答案:

答案 0 :(得分:2)

您收到此错误消息是因为您的Node版本低于10.0,并且不支持for await...of请注意,for await在这里无效,可以仅替换for 事实证明api确实需要它


添加: 在docs中进行操作:如果运行时支持,则可以使用for await of,也可以以老式的方式迭代可迭代对象

let containerItem = await result.next();
while (!containerItem.done) {
  console.log(`Container ${i++}: ${containerItem.value.name}`);
  containerItem = await iter.next();
}

答案 1 :(得分:0)

对此有一种解决方法:

const { BlobServiceClient } = require("@azure/storage-blob");

async function main() {
    try {
        const blobServiceClient = await BlobServiceClient.fromConnectionString('DefaultEndpointsProtocol=https;AccountName=devappsstorage;AccountKey=aw/FF01OIfnYmK6Bh+d4NIhvVBaDKn942O22YAMNycX/27qKVwYW+/Dma/C7pI+lvU0wpo/VBJ1jFd4yi3MMWw==;EndpointSuffix=core.windows.net');
        let i = 1;
        let iter = blobServiceClient.listContainers();
        let containerItem = await iter.next();
        while (!containerItem.done) {
            console.log(`Container ${i++}: ${containerItem.value.name}`);
            containerItem = await iter.next();
          }
    } catch (error) {
        console.log(error);
    }
}

main();