2016-05-16 84 views
0
const dbConnection = require("../dbConnection");  

var task = function() { 
    var response = ""; 
    dbConnection.then(function() { 
     //do something here 
     response = "some value";    
    }) 
    .catch(function() { 
     response = new Error("could not connect to DB"); 
    }); 

    //I can't return response here because the promise is not yet resolved/rejected. 
} 

我正在使用其他人编写的节点模块。它返回一个承诺。我想返回一个字符串或new Error(),具体取决于模块返回的Promise对象是否已解析。我怎样才能做到这一点?根据是否已解析Promise从函数返回值

我不能finally()回调中返回或者因为那return将适用于回调函数不是我task功能。

+0

为什么你不能原样使用该模块? –

回答

0

dbConnection.then().catch()本身会返回一个承诺。考虑到这一点,我们可以简单地将代码编写为return dbConnection.then(),并让代码使用该函数将返回值视为承诺。例如,

var task = function() { 
    return dbConnection.then(function() { 
    return "Good thing!" 
    }).catch(function() { 
    return new Error("Bad thing.") 
    }) 
} 

task().then(function(result){ 
    // Operate on the result 
} 
0
const dbConnection = require("../dbConnection");  

var task = function() { 
    var response = ""; 
    return dbConnection.then(function() { 
    //do something here 
    response = "some value"; 
    return response; 
    }) 
    .catch(function() { 
    response = new Error("could not connect to DB"); 
    return response; 
    }); 
} 

这将返回一个承诺,你可以再链条。

使用承诺的点是类似于使用回调。您不希望CPU坐在那里等待响应。