且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在数组的 forEach 循环中使用 promise 来填充对象

更新时间:2022-06-01 03:10:14

Promise.all() 在这里会有帮助:

var promises = [];

array.forEach(function(element) {
    promises.push(
        developer.getResources(element)
            .then((data) = > {
                name = data.items[0];
                return developer.getResourceContent(element, file);
            })
            .then((response) = > {
                fileContent = atob(response.content);
                self.files.push({
                    fileName: fileName,
                    fileType: fileType,
                    content: fileContent
                });
            }).catch ((error) = > {
                console.log('Error: ', error);
            })
    );
});

Promise.all(promises).then(() => 
    self.resultingFunction(self.files)
);

这会为每个项目启动 AJAX 调用,一旦调用完成,将每次调用的结果添加到 self.files 并调用 self.resultingFunction()在完成所有调用之后.

This starts the AJAX call for each of the items, adds the result of each call to self.files once the call is complete and calls self.resultingFunction() after all calls have been completed.

根据 Yury Tarabanko 的建议进行了简化.

Simplified based on Yury Tarabanko's suggestions.