简体   繁体   English

如何处理函数的承诺或变量返回

[英]How to handle both a promise or variable return from a function

Here is a simplified version of what I have:这是我所拥有的简化版本:

function test(thisBool){
   var response;
   if(thisBool){
      response = makeAPIrequest().then(function(){    
      }, function(err){ 
         console.log(err)
      })
   } else {
      response = "doesntmatter"
   }    
}

So if the parameter is true , make the api request.因此,如果参数为true ,则发出 api 请求。 If it's false , return the 'doesntmatter' string.如果为false ,则返回 'doesntmatter' 字符串。

When I call this, I wish to use the response in either instance.当我调用它时,我希望在任何一种情况下都使用响应。

var testResponseTrue = test(true);
var testResponseFalse = test(false);

Is there a way to do this?有没有办法做到这一点? Or will I have to do some callback functions somehow?或者我必须以某种方式做一些回调函数? I'm not sure of the best way to do this, any advice would help :)我不确定这样做的最佳方法,任何建议都会有所帮助:)

Return a promise for each condition.为每个条件返回一个 promise。 You already have a promise being returned from your api request method so you can use Promise.resolve() for the default您已经有一个从 api 请求方法返回的承诺,因此您可以使用Promise.resolve()作为默认值

 function makeApiRequest(){ // fake request ... use your normal method that already returns a prmise return new Promise(resolve=>{ setTimeout(function(){ resolve('Value from request') },500) }); } function test(thisBool){ return thisBool ? makeApiRequest() : Promise.resolve("Default value") } test(false).then(r => {console.log('False value:', r)}); test(true).then(r => {console.log('True value:', r)})

It makes it a bit complicated that your consumers would have to check if they now got a promise back or not.您的消费者必须检查他们现在是否得到了承诺,这让事情变得有点复杂。 I would rather choose to internally go for an autoresolving promise in case the boolean is false, so that you can handle the response in the same way as you would with a boolean that is true如果布尔值为假,我宁愿选择在内部进行自动解析承诺,这样您就可以像处理为真的布尔值一样处理响应

 // mock function makeAPIrequest() { return new Promise( (resolve) => setTimeout( () => resolve('done'), 100 ) ); } function test(thisBool){ return new Promise( (resolve, reject) => { if (thisBool) { makeAPIrequest().then( result => resolve(result) ).catch( err => reject(err) ); return; } setTimeout( () => resolve('does not matter'), 0); }); } test(true).then( response => console.log('response from true = ' + response ) ); test(false).then( response => console.log('response from false = ' + response ) );

If you really want to catch the values in variables, I guess you could also use the async/await pattern , like in the following snippet如果您真的想捕获变量中的值,我想您也可以使用async/await pattern ,如下面的代码片段所示

 (async () => { // mock function makeAPIrequest() { return new Promise( (resolve) => setTimeout( () => resolve('done'), 100 ) ); } let test = function async(thisBool){ return new Promise( (resolve, reject) => { if (thisBool) { makeAPIrequest().then( result => resolve(result) ).catch( err => reject(err) ); return; } setTimeout( () => resolve('does not matter'), 0); }); } var testResponse1 = await test(true); var testResponse2 = await test(false); console.log( testResponse1 ); console.log( testResponse2 ); })();

You should use callback or promises to handle such kind of scenarios.您应该使用回调或承诺来处理此类场景。 Below is code snippet for the same using callback:以下是使用回调的相同代码片段:

function test(thisBool, callback) {
    var response;
    if(thisBool) {
        makeAPIrequest()
        .then(function(response) {
            callback(response);    
        }, function(err) { 
            callback(err);
        })
    } else {
        response = "doesntmatter";
        callback(response);
    }    
}
test(true, function(testResponseTrue) {
    console.log(testResponseTrue);
});
test(false, function(testResponseFalse) {
    console.log(testResponseFalse);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM