我想做一些簡單的事情。如何在Javascript中處理未定義的返回?
func1(x).then(func2)
我不會使用來自func1
任何返回值(是的,在這種情況下func1
回報undefined
),我只想func1
後執行func2
,我怎麼想這樣做,因爲undefined
沒有財產then
?
謝謝!
我想做一些簡單的事情。如何在Javascript中處理未定義的返回?
func1(x).then(func2)
我不會使用來自func1
任何返回值(是的,在這種情況下func1
回報undefined
),我只想func1
後執行func2
,我怎麼想這樣做,因爲undefined
沒有財產then
?
謝謝!
由於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);
})
function a(callbackFunction){
console.log('The first function works');
collbackFunction();
}
function b(){
console.log('The second function works');
}
a(b);
您將在控制檯中看到: 「第一功能工作」和新行: 「第二個功能工作」
以任何方式'func1'異步...? – deceze
func1必須返回一個Promise .. – Keith
@Keith我的問題是,如果它不能返回一個承諾,我們可以從未定義的值創建一個默認的嗎? – xxx222