【问题标题】:resolving promise, stil then of undefined解决承诺,仍然是未定义的
【发布时间】:2019-07-29 21:51:58
【问题描述】:

我认为我解决了承诺,代码仍然在说未定义,它没有返回承诺,为什么?

export const SpacesPutImage = (folder, file, id, data, expertId, avatarUrl) => {

    console.log(folder, file, id, data, expertId, avatarUrl)
    if (avatarUrl === undefined) {
        console.log('si')
        return new Promise(function(resolve, reject) {

            apiCall('put', `/api/experts/${expertId}/spaces`, {
                    data: data,
                    size: file.size,
                    id: id,
                    folder: folder,
                    fileType: file.type
                })
                .then((res) => resolve(res.Location))
                .catch(err => reject(err))


        })
    } else {
        console.log('no')
        return new Promise(function(resolve, reject) {
            apiCall('put', `/api/experts/${expertId}/spaces/${avatarUrl.split("/")[4]}`, {
                    data: data,
                    size: file.size,
                    id: expertId,
                    folder: folder,
                    fileType: file.type
                }).then((res) => resolve(res.Location))
                .catch(err => reject(err))
        })

    }
}

【问题讨论】:

  • 如果可能,请发布真正的错误消息和可能的 apiCall 函数。
  • new Promise 中包装apiCall() 是一种反模式,因为apiCall() 本身会返回一个承诺
  • 您是否正确地等待返回的承诺? spacePutImage 的结果是否出现错误?

标签: javascript reactjs promise


【解决方案1】:

首先,你不需要new Promise,直接返回api调用即可,如果使用.then.catch就说明已经是promise了。

export const SpacesPutImage = (folder, file, id, data, expertId, avatarUrl) => {
    console.log(folder, file, id, data, expertId, avatarUrl)
    if (avatarUrl === undefined) {
        console.log('si')
        return apiCall('put', `/api/experts/${expertId}/spaces`, {
            data: data,
            size: file.size,
            id: id,
            folder: folder,
            fileType: file.type
        }).then(res => res.Location)       
    } else {
        console.log('no')
        return apiCall('put', `/api/experts/${expertId}/spaces/${avatarUrl.split("/")[4]}`, {
            data: data,
            size: file.size,
            id: expertId,
            folder: folder,
            fileType: file.type
         }).then(res => res.Location)
    }
}

请在您的问题中添加apiCall 是什么以及您在哪里打电话给SpacesPutImage

我认为我解决了承诺,代码仍然在说未定义

请提供正确的错误以及可能发生的位置。

正如 cmets 中所说,可能发生的一件事是 apiCall 不返回承诺,saying then of undefined 可能与 apiCall 不返回承诺有关。

【讨论】:

  • 没有解释为什么 OP 得到undefined
  • "如果它使用.then.catch 这意味着它已经是一个promise。" 但这是OP代码的问题,apiCall 不会返回一个承诺,它将解释“.then of undefined”错误。
  • @EmileBergeron 这是一个很好的观点。 OP的问题有太多缺失的部分,很难理解,甚至没有显示正确的错误。但这是一个很好的观察!
  • @charlietfl Would throw error 这可能是 OP 遇到的错误
  • @SvenBrodersen 好的,但你写的好像apiCall() 返回一个承诺而不是一个值,让所有人猜测实际的错误和问题是什么
猜你喜欢
  • 2020-11-22
  • 2022-01-27
  • 2020-05-18
  • 2020-03-16
  • 2021-01-03
  • 1970-01-01
  • 2020-10-22
  • 2014-12-15
  • 1970-01-01
相关资源
最近更新 更多