![](/img/trans.png)
[英]How do I tell if a function returns a Promise without executing the function?
[英]How do I check if a JavaScript function returns a Promise?
假設我有兩個功能:
function f1() {
return new Promise<any>((resolve, reject) => {
resolve(true);
});
}
function f2() {
}
我怎么知道f1
是否會返回Promise
而f2
不會?
調用函數,使用instanceof
let possiblePromise = f1();
let isPromise = possiblePromise instanceof Promise;
所以它只是關於標准化輸出。 然后通過Promise.resolve()
和 co 運行它。
var possiblePromise = f1();
var certainPromise = Promise.resolve(possiblePromise).then(...);
或者
var possiblePromises = [f1(), f2()];
Promise.all(possiblePromises).then(values => ...);
但是你需要對這些函數返回什么有一個基本的想法。 例如:兩個例子都會失敗
function f3(){
return [somePromise, someOtherPromise];
}
var arrayOfPromisesOrValues = f3();
//here you'll still deal with an Array of Promises in then();
Promise.resolve(arrayOfPromisesOrValues).then(console.log);
//neither does this one recognize the nested Promises
Promise.all([ f1(), f2(), f3() ]).then(console.log);
//only these will do:
Promise.all(f3()).then(console.log);
Promise.all([ f1(), f2(), Promise.all(f3()) ]).then(console.log);
您需要知道f3
返回一個 Promises 或值數組並處理它。 就像您需要知道f1
和f2
返回一個值或一個值的 Promise 一樣。
底線:您需要對函數返回的內容有基本的了解,才能通過正確的函數運行結果來解決 Promise。
這是做不到的。
但是,您可以將任何函數強制轉換為返回 Promise 的函數。 這就是我在這里要做的。
const toPromise = function (f) { return function () { return new Promise((resolve, reject) => { const result = f.apply(null, Array.from(arguments)); try { return result.then(resolve, reject); // promise. } catch (e) { if (e instanceof TypeError) { resolve(result); // resolve naked value. } else { reject(e); // pass unhandled exception to caller. } } }); }; }; const f = (x) => x; const g = (x) => Promise.resolve(x); const h = (x) => Promise.reject(x); // Naked value. toPromise(f)(1).then((x) => {console.log(x)}); // Resolved Promise. toPromise(g)(2).then((x) => {console.log(x)}); // Rejected Promise. toPromise(h)(3).catch((x) => {console.log(x)});
對於 NodeJS,我們可以使用util/types
內置模塊中的isPromise
函數。 鏈接到此處的文檔。
import { isPromise } from "util/types"; // assume the JS object you want to test is "obj" isPromise(obj);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.