2017-10-04 75 views
-2

我想做一些简单的事情。如何在Javascript中处理未定义的返回?

func1(x).then(func2)

我不会使用来自func1任何返回值(是的,在这种情况下func1回报undefined),我只想func1后执行func2,我怎么想这样做,因为undefined没有财产then

谢谢!

+1

以任何方式'func1'异步...? – deceze

+0

func1必须返回一个Promise .. – Keith

+0

@Keith我的问题是,如果它不能返回一个承诺,我们可以从未定义的值创建一个默认的吗? – xxx222

回答

-1

由于func1返回类型可能不是承诺,因此您必须将func1包装为必须返回承诺的新函数。

例子:https://jsfiddle.net/kingychiu/gewm60as/

假设你有以下功能FUNC1,它返回一个承诺或者基于布尔未定义:

function I_will_return_promise_or_undefined(bool){ 
    if(bool){ 
     return new Promise(function(resolve, reject){ 
     resolve(null); 
    }); 
    }else{ 
     return undefined 
    } 
} 

您可以包装FUNC1这样:

function wrapper(bool){ 
    return new Promise(function(resolve, reject){ 
    var temp = I_will_return_promise_or_undefined(bool); 
    if(temp === undefined){ 
     // resolve it 
     resolve(undefined); 
    }else{ 
     // chain promise 
     temp.then(function(val){ 
     resolve(val) 
     }); 
    } 
    }); 
} 

最后它是你想要的:

// null 
wrapper(true).then(function(val){ 
    console.log(true, val); 
}); 

// undefinded 
wrapper(false).then(function(val){ 
    console.log(false, val); 
}) 
-1
function a(callbackFunction){ 
    console.log('The first function works'); 
    collbackFunction(); 
} 
function b(){ 
    console.log('The second function works'); 
} 
a(b); 

您将在控制台中看到: “第一功能工作”和新行: “第二个功能工作”