如何使以下代码等待并在恢复之前准备好api调用?

时间:2017-06-16 03:23:38

标签: javascript

以下代码循环遍历formFields数组。有两种类型的字段:包含要上传的文件和不包含文件的字段。我记得排队"排队"字段和"完成"那些,所以我知道何时更新表格

const payload = {}
const fields = {
  queued: [],
  finished: []
}

formFields.forEach(field => {
  fields.queued.push(field)
  if (hasUploadFiles(field)) { // FOR FILE INPUTS
    utils.mapCallPromise(field.value, file => {
      api.uploadPhoto(file, field).then(uploadedPhoto => {
        payload[field.name] = uploadedPhoto
        fields.finished.push(field)
      })
    })
  } else {  // FOR NORMAL INPUTS
    payload[field.name] = field.value
    fields.finished.push(field)
  }
})

if (fields.queued.length === fields.finished.length) {
  console.log('use the payload to update the form')
}

问题是api.uploadPhotoif (fields.queued.length === fields.finished.length)之后触发

如何修改代码,以便在if (fields.queued.length === fields.finished.length)完成后触发api.uploadPhoto

更新

这是api.uploadPhotoutils.mapCallPromise

api.uploadPhoto = async (file = {}, field = {}) => {
  if (utils.includes(api.usServers, api.env)) {
    return await usImageUpload.toFirebase(file, field)
  } else {
    return await cnImageUpload.toQCloud(file, field.userId, field.sizes)
  }
}

utils.mapCallPromise = (object, callback) => {
  return new Promise((resolve, reject) => {
    return Array.prototype.slice.call(object).map(value => {
      return resolve(callback(value))
    })
  })
},

1 个答案:

答案 0 :(得分:1)

使用Promise.all和数组映射方法,您可以执行以下操作

Promise.all(formFields.map(field => {
    if (hasUploadFiles(field)) { // FOR FILE INPUTS
        return api.uploadPhoto(file, field).then(uploadedPhoto => {
            return {field, uploadedPhoto};
        });
    } else {  // FOR NORMAL INPUTS
        return {field};
    }
})).then(results => {
    //results is an array of objects that are either {field, uploadedPhoto} or just {field} 
});