编程语言
首页 > 编程语言> > javascript-NodeJS Promise(Q)-如果诺言失败,如何获取价值?

javascript-NodeJS Promise(Q)-如果诺言失败,如何获取价值?

作者:互联网

我开始在NodeJS项目中使用Promise,但遇到了一个问题.在阅读了Promises / A规范并进行了大量的搜索之后,对于需要访问在Promise链中产生的值的情况,我没有找到一个很好的解决方案.在我的示例中,我想检查是否在创建图像时发生错误,如果是,则要删除它.

码:

var Q = require('Q');
var fs = require('fs');

// This produces the imgPath
function makeImage() {
    var deferred = Q.defer();
    deferred.resolve("path/to/image");
    return deferred.promise;
}

function watermark(imgPath) {
    var deferred = Q.defer();
    deferred.resolve(imgPath);
    return deferred.promise;
}

// This function fails
function doSomeCoolThings(imgPath) {
    var deferred = Q.defer();
    deferred.reject(new Error("System is exploded"));
    return deferred.promise;
}

var fileExists = Q.denodeify(fs.readFile);
var deleteFile = Q.denodeify(fs.unlink);

// How do I get the imgPath here?
function deleteImageIfPresent(err) {
    return Q.fcall(function () {
        return imgPath !== undefined;
    })
        .then(fileExists)
        .then(deleteFile);
}

var iKnowThatSolution;

makeImage()
    // Thats not what I want
    //.then(function(imgPath) {
    //    iKnowThatSolution = imgPath;
    //})
    .then(watermark)
    .then(doSomeCoolThings)
    .fail(deleteImageIfPresent);

解决方法:

我推荐这种方法:

return makeImage().then(function (path) {
    return doSomeCoolThings(path)
    .finally(function () {
        return removeImage(path);
    });
});

假设您信任makeImage,removeImage和doSomeCoolThings来返回Q承诺并且永不抛出.否则,总会有Q.fcall消除这些问题.

如果您希望在成功的情况下保留图像,并且仅在出现故障时才将其删除,则抛出错误:

return Q.fcall(makeImage).then(function (path) {
    return Q.fcall(doSomeCoolThings, path)
    .catch(function (error) {
        return Q.fcall(removeImage, path)
        .thenReject(error);
    });
});

另外,代替:

var deferred = Q.defer();
deferred.resolve(x);
return deferred.promise;

您可以:

return Q.resolve(x);

标签:q,node-js,promise,javascript
来源: https://codeday.me/bug/20191030/1964340.html