多个Promise循环和 循环里面异步问题示例

export function obsPost(data = []) {
	return new Promise(function(resolve, reject) {
		if (!data || data.tempFilePaths.length <= 0) {
			return reject('上传正确数据!')
		}
		let linshi_arr = [],
			true_arr = [],
			fileName = '',
			suffix = '',
			path = '',
			tempName = '';

		for (let i in data.tempFiles) {
			fileName = data.tempFiles[i].name //文件名字
			suffix = fileName.substring(fileName.lastIndexOf(".") + 1)
			tempName = data.tempFilePaths[i]
			tempName = tempName.substring(tempName.lastIndexOf("/") + 1)
			path = suffix + '/' + tempName + '-' + (Date.parse(new Date()) / 1000) + '.' + suffix
			linshi_arr.push(new Promise(function(resolve1, reject1) {
				(function(path1,resolve1, reject1){
					uni.common.post(
						uni.common.apiServer + 'yin', {
							type: 'get_obs_key', //获取有多少题
							path:path1
						},
						true,
						(res) => {
							if (res.code == 200) {
								uni.uploadFile({
										url: res.data.url, //用你自己的 bucket 名替换星号
										filePath: data.tempFilePaths[i],
										name: 'file',
										formData: {
											'key': path1,
											'AccessKeyId': res.data.Accesskeyid,
											'Policy': res.data.Policy,
											'x-obs-acl': 'public-read',
											'content-type': '',
											'Signature': res.data.Signature
										},
										success() {
											true_arr.push(path1)
											resolve1()
										},fail() {
											reject1();
										}
									}
								)
							} else {
								reject1('上传失败');
							}
						},
						(e) => {
							console.log(e);
						}
					);
				})(path,resolve1, reject1)
			}))
		}
		Promise.all(linshi_arr).then((res) => {
			resolve( true_arr)
		}).catch((err) => {
			console.log(err);
			reject('上传失败');
		})
	});
}

你可能感兴趣的:(前端,javascript,开发语言)