【问题标题】:Returning a promise within a promise在承诺中返回承诺
【发布时间】:2017-02-17 14:27:06
【问题描述】:

在不将 promise 嵌套在新的 Promise 中并调用 resolve/reject 的情况下,获得所需结果的最简单的方法是什么?

例子

const transferFile = (fileName, bucketName)=>{
    const destinationBucket = gcs.bucket(bucketName);
    return exists =  destinationBucket.file(fileName).exists()
        .then(exists=>{
            if(exists[0]){
                return true;
            } else {

                // calling another method that returns a promise

                return file.move(destinationBucket)
                    .then(yay=>{

                        // return yay

                        return yay;
                    });

            }
        });

}

transferFile(image, 'bucketName')
    .then(exists=>{
        console.log(exists);
        transferFile(video, 'bucketName');
    })

    // getting undefined rather than yay

    .then(yay)...

我希望将 yay 值从 file.move 返回到基本承诺链。目前不会在基本承诺链中捕获来自file.move 的抛出错误,也不会传递yay 的值。

【问题讨论】:

  • 这行得通吗? return exists = destinationBucket.file(fileName) 如果您想查看错误,请添加拒绝处理程序。
  • 你不需要return transferFile(video, 'bucketName');吗?
  • Shilly,确实如此,并且 catch 处理程序位于承诺链的下游。虎三郎,谢谢。那是一个非常糟糕的大脑放屁。我应该睡一会哈哈。
  • 你应该在return之后删除那个全局变量assingment exists =
  • 贝尔吉,是的。只是为了测试它是否返回了正确的东西。不过很好:)

标签: javascript es6-promise


【解决方案1】:

transferFile 返回承诺,但您在第二次调用中将其丢弃。

请注意我在 then 函数中返回它。

transferFile(image, 'bucketName')
    .then(exists=>{
        console.log(exists);
        return transferFile(video, 'bucketName');
    })

    // getting undefined rather than yay

    .then(yay)...

【讨论】:

    猜你喜欢
    • 2016-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-05
    • 1970-01-01
    • 2023-01-27
    • 2015-11-27
    • 1970-01-01
    相关资源
    最近更新 更多